Thursday, October 25, 2007

Using GetFileAttributes to Test for File Existence

The Old New Thing - Superstition: Why is GetFileAttributes the way old-timers test file existence?

"If you ask an old-timer how to test for file existence, they'll say, "Use GetFileAttributes." This is still probably the quickest way to test for file existence, since it requires only a single call. Other methods such as FindFirstFile or CreateFile require a separate FindClose or CloseHandle call, which triggers another network round-trip, which adds to the cost.

...

I don't know if any network providers still implement this data path feature, but Windows code in general sticks to GetFileAttributes, because it's better to be safe than sorry."

This is a tip that will come in handy for me...

At work I have to deal with long, greater than MAXPATH, paths. So I've had to write my own "IO.File" class (and IO.Path and IO.Directory classes), using InterOp to wrap the "W" (Unicode) API's.

I just checked it and my File.Exists function is using the FindFirstFile(W) method mentioned above. Since the class is intended for usage across a network, executing simultaneously on many machines, called a good number of times, minimizing network IO is a good thing. This GetFileAttributes technique fits that bill nicely...

No comments: