Fotis E.
Fotis E.

Reputation: 23

Why I'm getting FileNotFoundException while the file does exist

I have a FileSystemWatcher which tracks if a new file is created. If yes I have a method which reads the file and does some things..
In the code below, I'm getting a FileNotFoundException but the path/file does exist! I already checked the path, the filename, etc. There's no clue why it doesn't find the file.
Also in debug mode, I verified that the path variable has the right path but when I'm forcing it to continue, somehow it runs but unfortunately in release mode it stops..

using (StreamReader reader = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), Encoding.Default))
{ 
    //my code
}

The error I'm getting is

An unhandled exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll Additional information: Could not find file 'myPathHere

Anybody can help?

Upvotes: 0

Views: 2480

Answers (1)

Luaan
Luaan

Reputation: 63772

FileSystemWatcher tells you when a file is created, yeah. But that doesn't mean the file is finished writing by that point - it most certainly isn't. When you're stepping through the code, you're giving the other process the time it needs to write and close the file - in the end, this is a concurrency issue, and concurrency issues tend to be hard to reproduce when debugging. The same way, by the time you get around to manually check, the file is long done - the problem is in the timing. And sadly, there is no way to use FileSystemWatcher to give you a note when the file is closed (and thus, ready to be used by your application).

You need to wait until the file is actually complete - a simple loop trying to open the file and waiting a bit when failing should work well enough :)

Upvotes: 1

Related Questions