Re: Obtaining exclusive access to file / file lock

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



On Sun, 17 Jun 2007 08:50:00 -0700, Speedy <Speedy@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote:

[...]
However, it doesn't work, other applications can still do anything they want
with the file including writing to it, renaming or moving it or deleting it.

In addition to what Richard wrote, I'll point out that if you are running Windows Vista, and you are accessing any one of a number of kinds of files, virtualization will cause your application instance to successfully open the file exclusively, without blocking access by other applications or users, because those other applications or users are not really accessing the same file on the disk.

Another possibility is that you don't keep the FileStream around long enough to check whether the file is locked. Note in Richard's sample, he calls Console.Read() to make sure that his code pauses execution before reaching the FileStream.Close() call. You're supposed to dispose/close the FileStream instance somewhere yourself when you're done with it, but even if you just don't keep the reference, I believe the FileStream will eventually (and some times fairly quickly) be closed on your behalf.

Basically, the code you posted will normally lock the file. If it appears not to, that means either it's not locking the file you think it is, or there's something wrong about the way you're checking to see if the file is locked.

Pete
.



Relevant Pages

  • Re: static filestream for saving Xml file, intermittent WinIOError exceptions..
    ... thanks for your helpful post. ... it was my impression that if i took out ... a static read+write filestream on the file, that other applications ...
    (microsoft.public.dotnet.framework.aspnet)
  • Re: read file without locking it.
    ... "John please don't spam me!" ... Open the 'FileStream' with 'FileShare.ReadWrite' specified, which will allow other applications to read and write to the file while your application is keeping it opened. ...
    (microsoft.public.dotnet.languages.vb)
  • Converting an application to work on a network
    ... I have converted a number of applications to enable them to work together on ... a network. ... FileStream fs = new FileStream; ... Hoverer, doing some tests I find out that the solution isn't working. ...
    (microsoft.public.dotnet.languages.csharp)