Click here to Skip to main content
15,885,914 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi all,

I've got myself a little problem whilst implementing the FileSystemWatcher Class. I have a text file that it is "watching" for me. When the file changes I have my app spit out the new line to my form. This works, but I tend to get an IOException when I run it without breakpoints in. I have the textfile open and am making changes manually at the moment. The problem arises when I have to read the textfile to obtain the number of lines and the new line information.

What's the correct way for me to handle this IOException? Can I use some form of wait command (I can't afford to miss a line update), or is there a more robust way to deal with this problem?



Your time and help will be greatly appreciated.

Danke,

Jib.
Posted

Im just guessing because you didn't supply the exception message, but it sounds like you're opening the file while the process that is writing to it still has it open.

Modify your code so that it retrys the file operations. If it gets an exception, wait a second or two and go back and try it again. You'll also want a bailout built into this since you probably don't want to your trying the same operation forever. There has to be a way out if the file isn't available at all for some reason.
 
Share this answer
 
Comments
Jibrohni 30-Dec-10 12:51pm    
Thanks Dave,

Might it help if I make sure it's open for reading only? Then perhaps it won't be locked.
fjdiewornncalwe 30-Dec-10 13:02pm    
Just trying to open it readonly may not help as the process that is writing to the file may have an exclusive lock on it still. Maybe just trap the IOException in a try-catch and then repeat the process a few times until you succeed in opening the file. I would add a delay in there of 1/10 sec. or so to give the write process time to finish. (This is a pretty hack-like fix, but it does work in some situations)
Jibrohni 30-Dec-10 13:04pm    
Ok thanks, I'll try that. I guess I can keep a line count so that I know if I've missed a line if necessary. I'll let you know how I get on. Thanks again.
Dave Kreskowiak 30-Dec-10 17:51pm    
That may help, but it may not be the open mode that's the problem. It's the Share permissions that the other process is granting when it opens the file. If the other process opens the file ShareDenyRead (or ShareDenyReadWrite), no other process (including yours) can open the file until the has been closed.
The file is getting updated very frequently so I had to implement a timer that checked it with a tick frequency of 1. I copy the original file and just deal with the copied file so I don't interrupt the original. - Jibrohni 1 sec ago
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900