Skip to content

Commit e63cadd

Browse files
committed
Added GladerFileHelpers IsFileLocked
1 parent 3ab9c09 commit e63cadd

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.IO;
4+
using System.Text;
5+
6+
namespace Glader.Essentials
7+
{
8+
public static class GladerFileHelpers
9+
{
10+
/// <summary>
11+
/// Indicates if the file is locked.
12+
/// Returns false if the file doesn't even exist.
13+
/// </summary>
14+
/// <param name="path">Path to the file.</param>
15+
/// <returns>True if the file appears to be locked.</returns>
16+
public static bool IsFileLocked(string path)
17+
{
18+
if(!File.Exists(path))
19+
return false;
20+
21+
try
22+
{
23+
using var stream = new FileStream(
24+
path,
25+
FileMode.Open,
26+
FileAccess.ReadWrite, // catch shares opened for write
27+
FileShare.None); // require exclusive access
28+
}
29+
catch(IOException ex) when(IsLockViolation(ex))
30+
{
31+
return true;
32+
}
33+
34+
return false;
35+
}
36+
37+
private static bool IsLockViolation(IOException ex)
38+
{
39+
// LOWORD of HResult is the Win32 error code:
40+
var code = ex.HResult & 0xFFFF;
41+
const int ERROR_SHARING_VIOLATION = 32;
42+
const int ERROR_LOCK_VIOLATION = 33;
43+
return code == ERROR_SHARING_VIOLATION || code == ERROR_LOCK_VIOLATION;
44+
}
45+
}
46+
}

0 commit comments

Comments
 (0)