开发者

How to get open write handles on a file using C#?

开发者 https://www.devze.com 2022-12-20 20:57 出处:网络
I\'m copying from a client computer to a server computer in a shared directory. My server detects the new file, and after the copying is complete it has to process it. The problem is that, when writin

I'm copying from a client computer to a server computer in a shared directory. My server detects the new file, and after the copying is complete it has to process it. The problem is that, when writing a big file and using FileSystemWatcher, you get no ind开发者_运维技巧ication whether the copying is done or not. The only way to check this is by trying to open the file (File.OpenRead/OpenWrite) and getting an exception. How can I get a notification that the copy is complete without resorting to exception handling as flow control?

My first thought is if I could detect when the handle used for writing to the file is closed, I could tell exactly when the copying is complete, but I'm not sure how to do that.


Instead of using this ad-hoc notification of polling FileSystemWatcher, why can't the client explicitly notify the server via a WCF service call (or whatever)? You could even make a simple EXE that the client has called NotifyServerFileUploaded.exe [name of file].

This way, there's no polling, no handle trickery, and no perf problems.


Copy the file to a temp file. When the copy is complete, rename. Renaming is atomic. Just make sure the server computer ignores the temp files.


Have you tried using FilesystemWatcher and the Created event?

myWatcher.NotifyFilter = NotifyFilters.Attributes | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Security | NotifyFilters.DirectoryName;


myWatcher.Created += new FileSystemEventHandler(watcher_Changed);


retry the file for exclusive read.

int maxRetry = 3;
int x = 0;
tryAgain:
try
{
    using (var fs = File.Open("file.txt", FileMode.Open, 
                                          FileAccess.Read, 
                                          FileShare.None))
    {
        // you have exclusive read here
    }
}
catch (IOException)
{
    if (x++ > maxRetry)
        throw;
    Thread.Sleep(500);
    goto tryAgain;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号