FileSystemWatcher - File used by another process
-
Hi, I've written a windows service to parse files.It uses the FileSystemWatcher class in C# to sniff a folder for particular type of files. But when the files were being processed, i repeatedly get the error "The process cannot access the file "AAA" because it is being used by another process". To overcome this problem, i added the following. lines of code
public bool ParseEnvFile(string strFilePath) { try { using(FileStream fs = new FileStream(strFilePath, FileMode.Open, FileAccess.Read, FileShare.Read)) { // Do some processing here fs.Close(); m_nReadAttempts = 0; } } catch(IOException ex) { if(m_nReadAttempts < 3) { Thread.Sleep(2000); m_nReadAttempts++; return ParseEnvFile(strFilePath); } else { throw ex; } } ..... }
But even this did not solve the problem. The exception still kept coming, though less frequently. So I was forced to add a Timer event(runs every 5 mins) that would pick up all the files that were left over because of the exception. Now, my problem is this: When a file gets created in the folder, sometimes both the OnFileCreated event and the timer event try to access the file at the same time. Within my service, I'm required to open the file in write mode and update some contents. I find that at times the file that gets created ends up as a 0KB file (Note: when it initially got created the file had some content in it)!!!! Any ideas on why this happens? Thanks for any help in resolving this problem.