0

Possible Duplicate:
Wait until file is unlocked in .NET

I have many cases where a program must wait until a file is unlocked by another process (e.g file being copied) before it can be used again. A standard solution is to wait for it iterating in a loop using Thread.Sleep(). I don't consider that kind nice. I've read it's possible to do it with the FileSystemWatcher of .NET (I'm using C#). Can anyone illustrate it? Thanks a lot for your replies!

Community
  • 1
  • 1
relapse
  • 31
  • 2
  • 6
  • no. FileSystemWatcher does not tell you when a file handle is released. – Sam Axe Jan 25 '13 at 07:02
  • But it fires a sertain event if a file is created. Couldn't that be a solution for my issue? – relapse Jan 25 '13 at 07:09
  • 1
    A file being unlocked is not the same as one being created. – xpda Jan 25 '13 at 07:10
  • 1
    In the general case, even if you can find a way to be notified that a file has become unlocked, by the time your code is running and making an attempt to acquire the file, it's possible that some other process has taken a new lock. You *have* to write code that reacts to the file being locked when you attempt to acquire it *anyway*. – Damien_The_Unbeliever Jan 25 '13 at 07:33
  • If another process takes a new lock while the program running, it's possible to avoid the interference with deregistration of the event: `code`watcher.EnableRaisingEvents = false;`code` – relapse Jan 25 '13 at 12:47

2 Answers2

2

FileSystemWatcher as the name suggests ,lets you watch for any events that occur when you change,create,delete,rename a file or folder

You cannot use FileSystemWatcher to check if the file is locked..

Anirudha
  • 32,393
  • 7
  • 68
  • 89
0
FileSystemWatcher _watcher;
int _watcherEventFiredCounter;

_watcher = new FileSystemWatcher {
    Path = @"C:\temp",
    NotifyFilter = NotifyFilters.LastWrite,
    Filter = "*.zip",
    EnableRaisingEvents = true
};

_watcher.Changed += OnChanged;


private void OnChanged(object sender, FileSystemEventArgs e)
{
    _watcherEventFiredCounter++;
    // The event is fired two times: on start copying and on finish copying
    if (_watcherEventFiredCounter == 2) {
        Console.WriteLine("Copying is finished now!");
        _watcherEventCounter = 0;
    }
}

Now the question is how can come back to the calling thread?

relapse
  • 31
  • 2
  • 6
  • You can may take a look at the answer I gave to the Original Question of which yours is a duplicate of: http://stackoverflow.com/a/42782410/6754146 – Florian K Mar 14 '17 at 09:49