Skip to content

File Locks in .Net

June 7, 2008

So I’m writing a logging framework and as a part of it I have to be able to save exceptions locally in case I can’t get them out to a proper webservice.  Since it’s possible (though unlikely) in web apps and multi-threaded winforms that the log file might be locked I wanted to put in a check to make sure the file was free and just generally impliment some multi-thread style locking on the log file.

There is absolutely no clean way to do this in .Net.  It more or less comes down to something like this.

private bool IsFileLocked(FileInfo file)
       {
           try
           {
               using (file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None))
               {
                   return false;
               }
           }
           catch (IOException)
           {
               return true;
           }
       }

 

As I understand it, it’s a problem with the underlying win32 api that there isn’t really anything good for .Net to use and doing it pInvoke style is, I’m told 20x times worse that suffering the overhead of a catch.

Hopefully this will save someone else the hours I spent reading up on the topic.

Advertisements
One Comment leave one →
  1. cyrus permalink
    June 11, 2008 1:47 pm

    I feared that this was the case. Thanks – you saved me some time.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: