/IO/Utilities/IOExtensions.cs |
@@ -4,6 +4,8 @@ |
// rights of fair usage, the disclaimer and warranty conditions. // |
/////////////////////////////////////////////////////////////////////////// |
|
using System; |
using System.Diagnostics; |
using System.IO; |
|
namespace wasSharpNET.IO.Utilities |
@@ -10,6 +12,34 @@ |
{ |
public static class IOExtensions |
{ |
/// <summary> |
/// Attempt to obtain a filestream by polling a file till the handle becomes available. |
/// </summary> |
/// <param name="path">the path to the file</param> |
/// <param name="mode">the file mode to use</param> |
/// <param name="access">the level of access to the file</param> |
/// <param name="share">the type of file share locking</param> |
/// <param name="timeout">the timeout in milliseconds to fail opening the file</param> |
/// <returns>a filestream if the file was opened successfully</returns> |
public static FileStream GetWriteStream(string path, FileMode mode, FileAccess access, FileShare share, |
int timeout) |
{ |
var time = Stopwatch.StartNew(); |
while (time.ElapsedMilliseconds < timeout) |
try |
{ |
return new FileStream(path, mode, access, share); |
} |
catch (IOException e) |
{ |
// access error |
if (e.HResult != -2147024864) |
throw; |
} |
|
throw new TimeoutException($"Failed to get a write handle to {path} within {timeout}ms."); |
} |
|
public static bool isRootedIn(this string path, string root) |
{ |
// Path is empty and root is empty. |
@@ -28,8 +58,8 @@ |
if (string.IsNullOrEmpty(path)) |
return true; |
|
DirectoryInfo p = new DirectoryInfo(path); |
DirectoryInfo r = new DirectoryInfo(root); |
var p = new DirectoryInfo(path); |
var r = new DirectoryInfo(root); |
|
return string.Equals(p.Parent?.FullName, r.Parent?.FullName) || isRootedIn(p.Parent?.FullName, root); |
} |
@@ -36,14 +66,12 @@ |
|
public static void Empty(this string directory) |
{ |
DirectoryInfo dir = new DirectoryInfo(directory); |
var dir = new DirectoryInfo(directory); |
|
foreach (FileInfo fi in dir.GetFiles()) |
{ |
foreach (var fi in dir.GetFiles()) |
fi.Delete(); |
} |
|
foreach (DirectoryInfo di in dir.GetDirectories()) |
foreach (var di in dir.GetDirectories()) |
{ |
Empty(di.FullName); |
di.Delete(); |