Skip to content

Commit d0cc4b9

Browse files
committed
fix(file): correct FileInUse logic and exception handling
1 parent 87a5517 commit d0cc4b9

File tree

1 file changed

+10
-13
lines changed

1 file changed

+10
-13
lines changed

SharpHelpers/SharpHelpers/FileHelper.cs

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -76,28 +76,25 @@ public static long GetFileLenght(this string url)
7676
/// <returns></returns>
7777
public static bool FileInUse(this string filePath)
7878
{
79-
FileStream stream = null;
79+
if (string.IsNullOrWhiteSpace(filePath) || !File.Exists(filePath)) return false;
8080

8181
try
8282
{
83-
var file = new FileInfo(filePath);
84-
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
83+
using (File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
84+
{
85+
// able to open exclusively ⇒ not in use
86+
return false;
87+
}
8588
}
8689
catch (IOException)
8790
{
88-
//the file is unavailable because it is:
89-
//still being written to
90-
//or being processed by another thread
91-
//or does not exist (has already been processed)
92-
return true;
91+
return true; // locked by another process or still being written
9392
}
94-
finally
93+
catch (UnauthorizedAccessException)
9594
{
96-
stream?.Close();
95+
// treat as "in use"/not exclusively openable
96+
return true;
9797
}
98-
99-
//file is not locked
100-
return false;
10198
}
10299

103100
/// <summary>

0 commit comments

Comments
 (0)