Is there a way to check for "exclusive" access to a file?

K

Kent P. Iler

Hi,

I have an application that watches a directory using FileSystemWatcher.
When a specific type of files comes over, I want to parse it and then move
it.

However, these files can be somewhat large, and the FTP process isn't
complete when I try to access the files. In those instances, an exception
is thrown when I try to access the file.

Is there a way that I can check to see if the files is ready for reading and
moving before I read it? That way I can wait until it's ready instead of
having the exception thrown.

Thanks.

-- Kent Iler
 
G

Guest

The OS should not allow you to open it exclusively until it has been written
and closed. You can trap the error and keep trying, in a loop with a timer,
until you get exclusive access. Another way I used to use was to try renaming
it and trapping the error in a loop until it worked. The OS will not allow
you to rename it until you have exclusive access.
 
N

NuTcAsE

Well the best way without resorting to unmanaged API calls is to wrap
the function which opens the file in a try catch block and use
FileShare.None as the share parameter to a FileStream object.

Example:

try {
using (FileStream fs = new FileStream (@"C:\MyFile.txt",
FileMode.Open, FileAccess.Read, FileShare.None)) {
//Code here...
}
} catch (IOException ioEx) {
//Exception handling here.
}

Using FileShare.None flag will make sure that when opening a file, the
process has exclusive access to the file.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top