File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed
src/Glader.Essentials.Common/File Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments