Checking if a file is locked in C# using Win32

Below is a simple, fast way you can check if a file is locked, using Interop to use a win32 function. I’ve found this method to be pretty fast, but I would caution, you should still have some error logic in your code in case in the window of time between you checking your file for availability and using your file, it should become locked. Below is the c# code:

Using:

using System;
using System.IO;
using System.Runtime.InteropServices;

And in your class:

  [DllImport("kernel32.dll")]
        private static extern Microsoft.Win32.SafeHandles.SafeFileHandle CreateFile(string lpFileName, System.UInt32 dwDesiredAccess, System.UInt32 dwShareMode, IntPtr pSecurityAttributes, System.UInt32 dwCreationDisposition, System.UInt32 dwFlagsAndAttributes, IntPtr hTemplateFile);

        private static readonly uint GENERIC_WRITE = 0x40000000;
        private static readonly uint OPEN_EXISTING = 3;

        [DllImport("kernel32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool CloseHandle(SafeHandle hObject);

        public static bool boolFileLocked(string fPath)
        {
            if (!File.Exists(fPath))
            {
                return false;
            }

            SafeHandle sHandle = null;

            try
            {
                sHandle = CreateFile(fPath, GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);

                bool inUse = sHandle.IsInvalid;

                return inUse;
            }
            finally
            {
                if (sHandle != null)
                {
                    CloseHandle(sHandle);
                }
            }
        }

To test, toss this into your Main:

long tStart = DateTime.Now.Ticks;
Console.WriteLine("start");
Console.WriteLine(boolFileLocked(@"c:\locked.xlsx"));
Console.WriteLine(string.Format("{0:n0}", DateTime.Now.Ticks - tStart));
tStart = DateTime.Now.Ticks;
Console.WriteLine(boolFileLocked(@"c:\unlocked.xls"));
Console.WriteLine(string.Format("{0:n0}", DateTime.Now.Ticks - tStart));
tStart = DateTime.Now.Ticks;
Console.WriteLine(boolFileLocked(@"c:\missing.xls"));
Console.WriteLine(string.Format("{0:n0}", DateTime.Now.Ticks - tStart));
Console.WriteLine("end");
Console.ReadLine();
Checking if a file is locked in C# using Win32

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 )

Connecting to %s