/// <summary> /// 等同于:System.IO.Directory.Delete() /// </summary> /// <param name="path"></param> /// <param name="recursive"></param> public static void Delete(string path, bool recursive = true) { RetryFile.CreateRetry().Run(() => { Directory.Delete(path, recursive); return(1); }); }
public static void Compress(List <Tuple <string, byte[]> > files, string zipPath) { if (files == null) { throw new ArgumentNullException(nameof(files)); } if (string.IsNullOrEmpty(zipPath)) { throw new ArgumentNullException(nameof(zipPath)); } RetryFile.Delete(zipPath); using (FileStream file = RetryFile.Create(zipPath)) { using (ZipArchive zip = new ZipArchive(file, ZipArchiveMode.Create, true, Encoding.UTF8)) { foreach (Tuple <string, byte[]> tuple in files) { var entry = zip.CreateEntry(tuple.Item1, CompressionLevel.Optimal); using (BinaryWriter writer = new BinaryWriter(entry.Open())) { writer.Write(tuple.Item2); } } } } }
/// <summary> /// 将指定的目录打包成ZIP文件 /// </summary> /// <param name="path"></param> /// <param name="zipPath"></param> public static void Compress(string path, string zipPath) { RetryFile.Delete(zipPath); // 直接调用 .NET framework ZipFile.CreateFromDirectory(path, zipPath); }
/// <summary> /// 删除过早的临时文件 /// </summary> /// <param name="path">包含临时文件的目录,删除时会查找所有子目录</param> /// <param name="timeAgo">指定一个时间间隔,超过这个时间间隔前的文件将被删除</param> /// <param name="topDirectoryOnly">是否只清除指定目录,不包含它的子目录</param> /// <returns>过程中所有遇到的异常</returns> public static List <Exception> DeleteOldFiles(string path, TimeSpan timeAgo, bool topDirectoryOnly = true) { List <Exception> list = new List <Exception>(); try { if (Directory.Exists(path) == false) { return(list); } SearchOption searchOption = topDirectoryOnly ? SearchOption.TopDirectoryOnly : SearchOption.AllDirectories; IEnumerable <string> files = Directory.EnumerateFiles(path, "*.*", searchOption); DateTime now = DateTime.Now; foreach (string file in files) { // 清除过程中,也有可能其它进程正在删除文件,所有文件不存在就忽略 if (RetryFile.Exists(file) == false) { continue; } // 以文件的最后修改时间做为对比标准 DateTime time = RetryFile.GetLastWriteTime(file); TimeSpan span = now - time; // 删除 指定时间 前的文件 if (span >= timeAgo) { try { //Console.WriteLine(file); RetryFile.Delete(file); } catch (Exception ex) { list.Add(ex); } } } } catch (Exception ex2) { list.Add(ex2); } return(list); }
/// <summary> /// 删除临时文件 /// </summary> /// <param name="path">要执行删除的根目录</param> /// <param name="timeAgo">一个时间间隔,表示需要删除多久前的文件</param> /// <param name="topDirectoryOnly">是否只扫描指定的根目录(不包含子目录),如果需要扫描子目录,请指定为 false</param> public void DeleteFiles(string path, TimeSpan timeAgo, bool topDirectoryOnly) { this.Count = 0; this.Exceptions.Clear(); if (string.IsNullOrEmpty(path) || Directory.Exists(path) == false) { return; } DateTime now = DateTime.Now; SearchOption searchOption = topDirectoryOnly ? SearchOption.TopDirectoryOnly : SearchOption.AllDirectories; try { IEnumerable <string> files = Directory.EnumerateFiles(path, "*.*", searchOption); foreach (string file in files) { // 清除过程中,也有可能其它进程正在删除文件,所有文件不存在就忽略 if (RetryFile.Exists(file) == false) { continue; } // 以文件的最后修改时间做为对比标准 DateTime time = RetryFile.GetLastWriteTime(file); TimeSpan span = now - time; // 删除 指定时间 前的文件 if (span >= timeAgo) { try { RetryFile.Delete(file); this.Count++; } catch (Exception ex) { this.Exceptions.Add(ex); } } } } catch (Exception ex2) { this.Exceptions.Add(ex2); } }
private static string HashFile(HashAlgorithm hash, string filePath) { if (string.IsNullOrEmpty(filePath)) { throw new ArgumentNullException(nameof(filePath)); } if (RetryFile.Exists(filePath) == false) { throw new FileNotFoundException("文件不存在:" + filePath); } using (FileStream fs = RetryFile.OpenRead(filePath)) { byte[] buffer = hash.ComputeHash(fs); return(buffer.ToHexString()); } }
/// <summary> /// 取消文件的只读设置 /// </summary> /// <param name="filePath"></param> /// <returns></returns> public static void ClearReadonly(string filePath) { FileAttributes attributes = RetryFile.GetAttributes(filePath); if (attributes.HasFlag(FileAttributes.ReadOnly) == false) { return; } // 清除只读属性 attributes &= ~FileAttributes.ReadOnly; CreateRetry().Run(() => { File.SetAttributes(filePath, attributes); return(1); }); }
/// <summary> /// 将ZIP文件解压缩到指定的目录 /// </summary> /// <param name="zipPath">需要解压缩的ZIP文件</param> /// <param name="extractPath">要释放的目录</param> public static void ExtractFiles(string zipPath, string extractPath) { //ZipFile.ExtractToDirectory(zipPath, extractPath); // .net framework 的实现版本中,如果要释放的文件已存在,会抛出异常,所以这里就不使用了。 if (string.IsNullOrEmpty(zipPath)) { throw new ArgumentNullException("zipPath"); } if (string.IsNullOrEmpty(extractPath)) { throw new ArgumentNullException("extractPath"); } using (ZipArchive archive = ZipFile.OpenRead(zipPath)) { foreach (ZipArchiveEntry entry in archive.Entries) { // 忽略目录 if (entry.FullName.EndsWith("/")) { string path = Path.Combine(extractPath, entry.FullName.TrimEnd('/')); if (Directory.Exists(path) == false) { Directory.CreateDirectory(path); } continue; } // 计算要释放到哪里 string targetFile = Path.Combine(extractPath, entry.FullName); // 如果要释放的目标目录不存在,就创建目标 string destPath = Path.GetDirectoryName(targetFile); Directory.CreateDirectory(destPath); // 如果目标文件已经存在,就删除 RetryFile.Delete(targetFile); // 释放文件 entry.ExtractToFile(targetFile, true); } } }
public static void Compress(List <Tuple <string, object> > files, string zipPath) { if (files == null) { throw new ArgumentNullException(nameof(files)); } if (string.IsNullOrEmpty(zipPath)) { throw new ArgumentNullException(nameof(zipPath)); } RetryFile.Delete(zipPath); using (FileStream file = RetryFile.Create(zipPath)) { using (ZipArchive zip = new ZipArchive(file, ZipArchiveMode.Create, true, Encoding.UTF8)) { foreach (Tuple <string, object> tuple in files) { var entry = zip.CreateEntry(tuple.Item1, CompressionLevel.Optimal); Type dataType = tuple.Item2.GetType(); if (dataType == typeof(string)) { using (var stream = entry.Open()) { using (FileStream fs = RetryFile.OpenRead((string)tuple.Item2)) { fs.CopyTo(stream); } } } else if (dataType == typeof(byte[])) { using (BinaryWriter writer = new BinaryWriter(entry.Open())) { writer.Write((byte[])tuple.Item2); } } else { // 暂且忽略错误的参数吧。 } } } } }
/// <summary> /// 快速计算文件哈希值(只计算文件开头部分) /// </summary> /// <param name="filePath">要计算哈希值的文件路径</param> /// <param name="headerLength">读取开头多长的部分,默认值:2M</param> /// <returns></returns> public static string FastHash(string filePath, int headerLength = 2 * 1024 * 1024) { if (string.IsNullOrEmpty(filePath)) { throw new ArgumentNullException(nameof(filePath)); } if (RetryFile.Exists(filePath) == false) { throw new FileNotFoundException("文件不存在:" + filePath); } if (headerLength <= 0) { throw new ArgumentOutOfRangeException(nameof(headerLength)); } using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider()) { using (FileStream file = RetryFile.OpenRead(filePath)) { if (headerLength > file.Length) { headerLength = (int)file.Length; } // 将文件长度转成字节数组 byte[] intBytes = BitConverter.GetBytes(file.Length); if (BitConverter.IsLittleEndian) { Array.Reverse(intBytes); } // 申请字节缓冲区 byte[] buffer = new byte[headerLength + intBytes.Length]; Array.Copy(intBytes, buffer, intBytes.Length); // 读取文件的开头部分 file.Read(buffer, intBytes.Length, headerLength); // 计算缓冲区的哈希值 byte[] result = md5.ComputeHash(buffer); return(BitConverter.ToString(result).Replace("-", "")); } } }
/// <summary> /// 等同于:System.IO.Directory.GetFiles() /// </summary> /// <param name="path"></param> /// <param name="searchPattern"></param> /// <param name="searchOption"></param> /// <returns></returns> public static string[] GetFiles(string path, string searchPattern, SearchOption searchOption) { return(RetryFile.CreateRetry().Run(() => { return Directory.GetFiles(path, searchPattern, searchOption); })); }
/// <summary> /// 等同于:System.IO.Directory.CreateDirectory() /// </summary> /// <param name="path"></param> /// <returns></returns> public static DirectoryInfo CreateDirectory(string path) { return(RetryFile.CreateRetry().Run(() => { return Directory.CreateDirectory(path); })); }
/// <summary> /// 等同于:System.IO.Directory.GetLastWriteTime() /// </summary> /// <param name="path"></param> /// <returns></returns> public static DateTime GetLastWriteTime(string path) { return(RetryFile.CreateRetry().Run(() => { return Directory.GetLastWriteTime(path); })); }
/// <summary> /// 判断文件是否为隐藏文件 /// </summary> /// <param name="filePath"></param> /// <returns></returns> public static bool IsHidden(string filePath) { return(RetryFile.GetAttributes(filePath).HasFlag(FileAttributes.Hidden)); }