Last active
May 8, 2018 06:46
-
-
Save demius/781d4bc411b1669dcd16397e5f2147eb to your computer and use it in GitHub Desktop.
C# Win32 lock checking
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
internal static class FileInspector | |
{ | |
[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); | |
/// <summary> | |
/// Determines whether the specified file is currently in use by another process | |
/// </summary> | |
/// <param name="path">The full local path of the file to inspect</param> | |
/// <returns>True if the file exists and is currently locked, otherwise false.</returns> | |
public static bool Locked(string path) | |
{ | |
if (!File.Exists(path)) | |
return false; | |
SafeHandle handle = null; | |
try | |
{ | |
handle = CreateFile(path, GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero); | |
return handle.IsInvalid; | |
} | |
finally | |
{ | |
if(handle != null) | |
{ | |
CloseHandle(handle); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment