Reputation: 15
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");
}
Upvotes: 0
Views: 196
Reputation: 11963
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!
Upvotes: 3