By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,299 Members | 1,225 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,299 IT Pros & Developers. It's quick & easy.

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

P: n/a

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

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.


-- Kent Iler
Please CC: all replies via e-mail
Remove .NOSPAM from e-mail address
Jul 22 '05 #1
Share this Question
Share on Google+
2 Replies

P: n/a
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.
Jul 22 '05 #2

P: n/a
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.


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.

Jul 22 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.