469,887 Members | 1,217 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,887 developers. It's quick & easy.

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


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
2 2170
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
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.

Similar topics

2 posts views Thread by Dave Reid | last post: by
18 posts views Thread by Andre Laplume via AccessMonster.com | last post: by
5 posts views Thread by =?Utf-8?B?U3BlZWR5?= | last post: by
reply views Thread by Salome Sato | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.