Opening Files Exclusively

  • Thread starter Thread starter PM
  • Start date Start date
P

PM

Has anyone found a way to open a file exclusively where it
will fail if the file is already open, i have tried the
following
_FileStream = new FileStream(@"C:\Data.txt",
FileMode.Open, FileAccess.ReadWrite, FileShare.None);
which does not prevent me from opening the file even if
another user has the file open ie Notepad, it will prevent
me from saving the file in notepad until i close the file
in the app. I can then save changes made in notepad.

ie
Open file with notepad
Open file with app (Above line)
Clsoe file in app
Close file with changes from notepad

I want to prevent the second step so that i can only open
the file if no other process has the file open.



Thanks in advance
Pat
 
Just curious, can you do this sequence of steps:

Open file with app
Open file with notepad
.....
?

I have a feeling that the FileShare.None will only apply to opening the file
again *after* locking it, so since Notepad doesn't lock the file, it won't
stop you opening it again. But I'm kind of guessing here.
 
Works exactly as you have indicated, that is the
FileShare.None will prevent notepad from opening the file,
my problem is that if the file is already open wuth
notepad (No lock) and i open the file from my app, saving
my changes and notepad then saves changes, my app changes
will have been lost. I'm just looking at trying to prevent
my app from opening the file if the file is already open,
this way i avoid this possibility.

Thanks for the reply.
Pat
 
I understand the problem and I don't know of a way to tell if the file has
already been opened, not within the .NET framework. You could use the
FileSystemWatcher class to detect changes to a file, but that still doesn't
tell you if it was opened, only if it is changed, deleted, renamed, etc. You
could also use the FileInfo.LastAccessTime to see when the file was last
opened, but it still won't tell you if it's still open.
I think the problem is that even if notepad is still open with your file,
the file itself is probably already closed. i.e. Notepad opens the file,
reads it, then closes the file. It doesn't open it again until the user hits
save. So, technically the file is closed.
 
Pat,
But does Notepad keep the file open?

I was under the impression that when you use File Open in Notepad, that
Notepad opens the file, reads the entire file into memory, then closes the
file. Later when you use File Save in Notepad, that Notepad again opens the
file, writer to the file, then closes the file.

Hence when you use FileShare.None the file is not physically open, hence it
works. Later when Notepad tries to save its copy it fails.

Hope this helps
Jay
 
Seems to work exactly as you say, i hadn't tought about
the way notepad works with a files contents.

Thanks for the help Matt and Jay
I Appreciate it
Pat
 
Back
Top