/////////////////////////////////////////////////////////////////////////// // 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 { /// /// Attempt to obtain a filestream by polling a file till the handle becomes available. /// /// the path to the file /// the file mode to use /// the level of access to the file /// the type of file share locking /// the timeout in milliseconds to fail opening the file /// a filestream if the file was opened successfully 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(); } } } }