wasSharpNET – Rev 27
?pathlinks?
///////////////////////////////////////////////////////////////////////////
// Copyright (C) Wizardry and Steamworks 2017 - License: GNU GPLv3 //
// Please see: http://www.gnu.org/licenses/gpl.html for legal details, //
// rights of fair usage, the disclaimer and warranty conditions. //
///////////////////////////////////////////////////////////////////////////
using System;
using System.Diagnostics;
using System.IO;
namespace wasSharpNET.IO.Utilities
{
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.
if (string.IsNullOrEmpty(path) && string.IsNullOrEmpty(root))
return true;
// Path is empty but the root path is not empty.
if (string.IsNullOrEmpty(path) && !string.IsNullOrEmpty(root))
return true;
// The supplied root path is empty.
if (string.IsNullOrEmpty(root))
return false;
// The path is empty and the root is not.
if (string.IsNullOrEmpty(path))
return true;
var p = new DirectoryInfo(path);
var r = new DirectoryInfo(root);
return string.Equals(p.Parent?.FullName, r.Parent?.FullName) || isRootedIn(p.Parent?.FullName, root);
}
public static void Empty(this string directory)
{
var dir = new DirectoryInfo(directory);
foreach (var fi in dir.GetFiles())
fi.Delete();
foreach (var di in dir.GetDirectories())
{
Empty(di.FullName);
di.Delete();
}
}
}
}
Generated by GNU Enscript 1.6.5.90.