0

I am using a FileSystemWatcher to detect a file. Once it detects the file, I want to read the contents and store it in a string. But when trying to read the contents I get process already in use.

Here is my code:

var watcher = new FileSystemWatcher(b);
watcher.EnableRaisingEvents = true;
watcher.Path = Path.GetDirectoryName(b + "CMDExec.txt");
watcher.Filter = Path.GetFileName(b + "CMDExec.txt");
watcher.Created += Watcher_Created;

private void Watcher_Created(object sender, FileSystemEventArgs e)
{
    string b = Path.GetTempPath();
    string text = System.IO.File.ReadAllText(b + "CMDExec.txt");
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Steve's answer is on point, so I won't provide additional elaboration. However, I think its useful to point you towards the thought process that would most easily resolve your issue: [See this Q&A](https://stackoverflow.com/questions/10982104/wait-until-file-is-completely-written) for a good jumping off point. – gravity Jan 31 '19 at 19:14

1 Answers1

3

you have to understand how the File IO lock works in this case.

Lets call the process creating the file process A

Process A would first Create the File and acquire an exclusive lock on the file to write contents to it

Once this happened you will get a file created event to indicate that the file has been created. But at this point of time process A still holds the exclusive lock on the file because it has not finish writing the content yet.

If you have direct access to the writer process you can make some signaling to your program to indicate that the file is done and is ready to consume. Or you will have to do some error handling to try again until you can successfully read the file.

But do be aware that your read will acquire a shared read lock on the file preventing any other process to acquire exclusive lock until the read is done. So if process A tries to exclusively lock the file again it will fail and might crash if it did not handle it correctly.

Welcome to the world of concurrency and race condition!

Steve
  • 11,696
  • 7
  • 43
  • 81
  • Sometimes i question what im doing with my life haha, Thanks for your help ill look into it. Would a delay work? – Best Exploits Jan 31 '19 at 18:55
  • @BestExploits it will help but its not a guarantee. And the original process might get into trouble if it tries to access the file again before your read ends. so there is no definitive answer here, all situational based on what you are doing and what A is doing. – Steve Jan 31 '19 at 18:58
  • Okay, It works! Thanks for everything, have a nice day/night. – Best Exploits Jan 31 '19 at 19:01