using ICSharpCode.SharpZipLib.BZip2; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using ICSharpCode.SharpZipLib.Zip; using System.Text.RegularExpressions; using System.Security.Cryptography; using System.Web; namespace Pcb.Common { /// /// 通用常规文件操作 /// public class FileCommonHelper { //使用BZIP解压文件的方法 public static bool UnBzipFile(string zipfilename, string unzipfilename) { bool blResult;//表示解压是否成功的返回结果 //为压缩文件创建文件流实例,作为解压方法的输入流参数 FileStream zipFile = File.OpenRead(zipfilename); //为目标文件创建文件流实例,作为解压方法的输出流参数 FileStream destFile = File.Open(unzipfilename, FileMode.Create); try { BZip2.Decompress(zipFile, destFile);//解压文件 blResult = true; } catch (Exception ee) { Console.WriteLine(ee.Message); blResult = false; } destFile.Close();//关闭目标文件流 zipFile.Close();//关闭压缩文件流 return blResult; } // /// 压缩指定文件生成ZIP文件 /// /// 顶层文件夹名称 \Storage Card\PDADataExchange\send\xml\ /// 待压缩文件列表 file名 ddd.txt /// ZIP文件 \Storage Card\PDADataExchange\send\zip\version.zip /// 压缩比 7 /// 密码 "" /// 压缩文件注释文字 "" public static void ZipFile(string[] fileNamesToZip, string ZipedFileName, int CompressionLevel, string password, string comment, List listName) { using (ZipOutputStream s = new ZipOutputStream(System.IO.File.Open(ZipedFileName, FileMode.Create))) { if (password != null && password.Length > 0) s.Password = password; if (comment != null && comment.Length > 0) s.SetComment(comment); s.SetLevel(CompressionLevel); // 0 - means store only to 9 - means best compression for (int i = 0; i < fileNamesToZip.Length; i++) { string file = fileNamesToZip[i]; using (FileStream fs = File.OpenRead(file)) //打开待压缩文件 { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); //读取文件流 ZipEntry entry = new ZipEntry(listName[i]); //新建实例 entry.DateTime = DateTime.Now; // entry.IsUnicodeText = true; entry.Size = fs.Length; fs.Close(); s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); } } s.Finish(); s.Close(); } } #region 读取指定目录下的文件(包含子文件夹及文件) /// /// 读取指定目录下的文件(包含子文件夹及文件)返回相对路径列表 /// /// 目录 /// 提取通过验证的文件(只读取通过验证的文件名) public static List ReadFiles(string Dir, Regex IncludeNameReg = null) { return ReadFiles(new DirectoryInfo(Dir), IncludeNameReg); } /// /// 读取指定目录下的文件(包含子文件夹及文件)返回相对路径列表 /// /// 目录 /// 提取通过验证的文件(只验证文件名) public static List ReadFiles(DirectoryInfo Dir, Regex IncludeNameReg = null) { List files = new List(); Func fn; if (IncludeNameReg == null) { fn = (f) => true; } else { fn = (f) => IncludeNameReg.IsMatch(f.Name); } ReadFiles(Dir, ref files, fn, ""); return files; } private static void ReadFiles(DirectoryInfo dir, ref List files, Func filter, string relPath) { if (!dir.Exists) { return; } foreach (DirectoryInfo di in dir.GetDirectories()) { ReadFiles(di, ref files, filter, relPath + di.Name + "\\"); } foreach (FileInfo fi in dir.GetFiles()) { if (filter(fi)) { files.Add(relPath + fi.Name); } } } /// /// 读取指定目录下的文件信息列表 /// /// 目录 /// 文件处理方法 public static void ReadFiles(string Dir, Action FileEval) { ReadFiles(new DirectoryInfo(Dir), FileEval, t => { }); } /// /// 读取指定目录下的文件信息列表 /// /// 目录 /// 文件处理方法 /// 目录处理方法 public static void ReadFiles(DirectoryInfo Dir, Action FileEval, Action DirEval) { if (!Dir.Exists) { return; } foreach (DirectoryInfo d in Dir.GetDirectories()) { ReadFiles(d, FileEval, DirEval); } foreach (FileInfo f in Dir.GetFiles()) { FileEval(Dir, f); } } #endregion #region 复制文件夹(包含子文件夹及文件) /// /// 获取文件夹对象 /// /// 文件夹路径 /// 文件夹对象 public static DirectoryInfo GetDir(string Dir) { DirectoryInfo di; if (!Directory.Exists(Dir)) { di = Directory.CreateDirectory(Dir); } else { di = new DirectoryInfo(Dir); } return di; } /// /// 复制文件夹、子文件夹及文件(包含子文件夹及文件) /// /// 源目录信息 /// 目标目录信息 /// 是否替换目标目录中已存在文件 /// 包含文件正则条件 /// 文件个数 public static int CopyDir(string SrcDir, string TgtDir, bool IsReplace, Regex IncludeFileReg = null) { return CopyDir(new DirectoryInfo(SrcDir), TgtDir, IsReplace, null, IncludeFileReg); } /// /// 复制文件夹、子文件夹及文件(包含子文件夹及文件) /// /// 源目录信息 /// 目标目录信息 /// 是否替换目标目录中已存在文件 /// 包含文件夹正则条件 /// 包含文件正则条件 /// 文件个数 public static int CopyDir(DirectoryInfo SrcDirInfo, string TgtDir, bool IsReplace, Regex IncludeDirReg = null, Regex IncludeFileReg = null) { Func fnd; Func fnf; if (IncludeDirReg == null) { fnd = d => false; } else { fnd = d => !IncludeDirReg.IsMatch(d.Name); } if (IncludeFileReg == null) { fnf = d => false; } else { fnf = d => !IncludeDirReg.IsMatch(d.Name); } return CopyDir(SrcDirInfo, GetDir(TgtDir), IsReplace, fnd, fnf); } /// /// 移动文件夹、子文件夹及文件(包含子文件夹及文件) /// /// 源目录 /// 目标目录 /// 是否替换 /// 排除目录函数 /// 排除文件函数 /// 重写文件名函数(传入参数只包含文件名+扩展名,不包含目录) /// 数量 public static int CopyDir(string SrcDir, string TgtDir, bool IsReplace, Func ExcludeDirFn, Func ExcludeFileFn, Func RenameFileNameFn = null) { return CopyDir(new DirectoryInfo(SrcDir), new DirectoryInfo(TgtDir), IsReplace, ExcludeDirFn, ExcludeFileFn, RenameFileNameFn); } /// /// 移动文件夹、子文件夹及文件(包含子文件夹及文件) /// /// 源目录 /// 目标目录 /// 是否替换 /// 排除目录函数 /// 排除文件函数 /// 重写文件夹名函数(传入参数只包含文件夹名) /// 重写文件名函数(传入参数只包含文件名+扩展名,不包含目录) /// 数量 public static int CopyDir(string SrcDir, string TgtDir, bool IsReplace, Func ExcludeDirFn, Func ExcludeFileFn, Func RenameDirNameFn, Func RenameFileNameFn = null) { return CopyDir(new DirectoryInfo(SrcDir), new DirectoryInfo(TgtDir), IsReplace, ExcludeDirFn, ExcludeFileFn, RenameDirNameFn, RenameFileNameFn); } /// /// 移动文件夹、子文件夹及文件(包含子文件夹及文件) /// /// 源目录信息 /// 目标目录信息 /// 是否替换 /// 排除目录函数 /// 排除文件函数 /// 重写文件名函数(传入参数只包含文件名+扩展名,不包含目录) /// 数量 public static int CopyDir(DirectoryInfo SrcDirInfo, DirectoryInfo TgtDirInfo, bool IsReplace, Func ExcludeDirFn, Func ExcludeFileFn, Func RenameFileNameFn = null) { if (!SrcDirInfo.Exists) { return 0; } string relpath = ""; if (RenameFileNameFn == null) { return CopyDir(SrcDirInfo, TgtDirInfo, IsReplace, ref relpath, ExcludeDirFn, ExcludeFileFn, s => s); } else { return CopyDir(SrcDirInfo, TgtDirInfo, IsReplace, ref relpath, ExcludeDirFn, ExcludeFileFn, RenameFileNameFn); } } /// /// 移动文件夹、子文件夹及文件(包含子文件夹及文件) /// /// 源目录信息 /// 目标目录信息 /// 是否替换 /// 排除目录函数 /// 排除文件函数 /// 重写文件夹名函数(传入参数只包含文件夹名) /// 重写文件名函数(传入参数只包含文件名+扩展名,不包含目录) /// 数量 public static int CopyDir(DirectoryInfo SrcDirInfo, DirectoryInfo TgtDirInfo, bool IsReplace, Func ExcludeDirFn, Func ExcludeFileFn, Func RenameDirNameFn, Func RenameFileNameFn = null) { if (RenameDirNameFn == null) { return CopyDir(SrcDirInfo, TgtDirInfo, IsReplace, ExcludeDirFn, ExcludeFileFn, RenameFileNameFn); } if (!SrcDirInfo.Exists) { return 0; } string relpath = ""; if (RenameFileNameFn == null) { return CopyDir(SrcDirInfo, TgtDirInfo, IsReplace, ref relpath, ExcludeDirFn, ExcludeFileFn, RenameDirNameFn, s => s); } else { return CopyDir(SrcDirInfo, TgtDirInfo, IsReplace, ref relpath, ExcludeDirFn, ExcludeFileFn, RenameDirNameFn, RenameFileNameFn); } } /// /// 复制文件目录及子目录的文件 /// /// 源目录 /// 目标目录 /// 是否替换 /// 相对路径 /// 排除目录函数 /// 排除文件函数 /// 重写文件名函数(传入参数只包含文件名+扩展名,不包含目录) private static int CopyDir(DirectoryInfo SrcDirInfo, DirectoryInfo TgtDirInfo, bool IsReplace, ref string RelPath, Func ExcludeDirFn, Func ExcludeFileFn, Func RenameFileNameFn) { return CopyDir(SrcDirInfo, TgtDirInfo, IsReplace, ref RelPath, ExcludeDirFn, ExcludeFileFn, s => s, RenameFileNameFn); } /// /// 复制文件目录及子目录的文件 /// /// 源目录 /// 目标目录 /// 是否替换 /// 相对路径 /// 排除目录函数 /// 排除文件函数 /// 重写文件夹名函数(传入参数只包含文件夹名,不包含目录) /// 重写文件名函数(传入参数只包含文件名+扩展名,不包含目录) private static int CopyDir(DirectoryInfo SrcDirInfo, DirectoryInfo TgtDirInfo, bool IsReplace, ref string RelPath, Func ExcludeDirFn, Func ExcludeFileFn, Func RenameDirNameFn, Func RenameFileNameFn) { int intCount = 0; DirectoryInfo diS = SrcDirInfo; string dirt = TgtDirInfo.FullName + "\\"; //递归执行 foreach (DirectoryInfo dir in diS.GetDirectories()) { if (ExcludeDirFn(dir)) { continue; } string newdir = RenameDirNameFn(dir.Name); string strT = RelPath + newdir + "\\", strT2 = dirt + newdir + "\\"; DirectoryInfo dit = new DirectoryInfo(strT2); if (!dit.Exists) { dit = Directory.CreateDirectory(strT2); } intCount += CopyDir(dir, dit, IsReplace, ref strT, ExcludeDirFn, ExcludeFileFn, RenameDirNameFn, RenameFileNameFn); } //替换文件 foreach (FileInfo file in diS.GetFiles()) { if (ExcludeFileFn(file)) { continue; } FileInfo tfile = new FileInfo(dirt + RenameFileNameFn(file.Name)); if (tfile.Exists) { if (!IsReplace) { continue; } tfile.Attributes = FileAttributes.Normal; tfile.Delete(); } file.CopyTo(tfile.FullName, true).Attributes = FileAttributes.Normal; intCount++; } //不存文件则删除文件夹 if (TgtDirInfo.GetFiles().Length == 0 && TgtDirInfo.GetDirectories().Length == 0) { TgtDirInfo.Delete(); } return intCount; } /// /// 复制文件到指定目录 /// /// 源目录 /// 目标目录 /// 是否目标文件替换 /// 排除目录函数 /// 排除文件函数 /// 重写文件名函数(传入参数只包含文件名+扩展名,不包含目录) /// 总复制数 public static int CopyDir(DirectoryInfo SrcDirInfo, DirectoryInfo TgtDirInfo, bool IsReplace, Func ExcludeDirFn, Func ExcludeFileFn, Func RenameFileNameFn = null) { if (!SrcDirInfo.Exists) { return 0; } string relpath = ""; if (RenameFileNameFn == null) { return CopyDir(SrcDirInfo, TgtDirInfo, IsReplace, ref relpath, ExcludeDirFn, ExcludeFileFn, s => s); } else { return CopyDir(SrcDirInfo, TgtDirInfo, IsReplace, ref relpath, ExcludeDirFn, ExcludeFileFn, RenameFileNameFn); } } /// /// 复制文件目录及子目录的文件 /// /// 源目录 /// 目标目录 /// 是否替换 /// 相对路径 /// 排除目录函数 /// 排除文件函数 /// 重写文件名函数(传入参数只包含文件名+扩展名,不包含目录) /// 总复制数 private static int CopyDir(DirectoryInfo SrcDirInfo, DirectoryInfo TgtDirInfo, bool IsReplace, ref string RelPath, Func ExcludeDirFn, Func ExcludeFileFn, Func RenameFileNameFn) { int intCount = 0; DirectoryInfo diS = SrcDirInfo; //递归执行 foreach (DirectoryInfo dir in diS.GetDirectories()) { string dirt = TgtDirInfo.FullName + dir + "\\"; if (ExcludeDirFn(dir)) { continue; } var dit = new DirectoryInfo(dirt); if (!dit.Exists) { dit = Directory.CreateDirectory(dirt); } string reldir = RelPath + dir + "\\"; intCount += CopyDir(dir, dit, IsReplace, ref reldir, ExcludeDirFn, ExcludeFileFn, RenameFileNameFn); } //替换文件 foreach (FileInfo file in diS.GetFiles()) { FileInfo fit = new FileInfo(TgtDirInfo.FullName + RenameFileNameFn(file.Name)); if (ExcludeFileFn(file, fit)) { continue; } if (fit.Exists) { if (!IsReplace) { continue; } fit.Attributes = FileAttributes.Normal; fit.Delete(); } file.CopyTo(fit.FullName, true).Attributes = FileAttributes.Normal; intCount++; } //不存文件则删除文件夹 if (TgtDirInfo.GetFiles().Length == 0 && TgtDirInfo.GetDirectories().Length == 0) { TgtDirInfo.Delete(); } return intCount; } #endregion #region 清理文件夹(包含子文件夹及文件,保留当前文件夹) /// /// 清理文件夹(包含子文件夹及文件,保留当前文件夹) /// /// 目录 /// 排除文件列表(文件名为小写且不包启路径) /// 文件数量 public static int ClearDir(string Dir, HashSet ExcludeFiles = null) { return ClearDir(new DirectoryInfo(Dir), ExcludeFiles); } /// /// 清理文件夹(包含子文件夹及文件,保留当前文件夹) /// /// 目录信息 /// 排除文件列表(文件名为小写且不包启路径) /// 文件数量 public static int ClearDir(DirectoryInfo DirInfo, HashSet ExcludeFiles = null) { if (!DirInfo.Exists) { return 0; } int DirCount = 0, FileCount = 0; if (ExcludeFiles == null) { ClearDir(DirInfo, ref DirCount, ref FileCount); } else { ClearDir(DirInfo, ExcludeFiles, ref DirCount, ref FileCount); } return FileCount; } /// /// 清理目录 /// /// 目录信息 /// 清理目录数(用于返回) /// 清理文件数(用于返回) static void ClearDir(DirectoryInfo DirInfo, ref int DirCount, ref int FileCount) { foreach (FileInfo fi in DirInfo.GetFiles()) { fi.Attributes = FileAttributes.Normal; fi.Delete(); FileCount++; } foreach (DirectoryInfo di in DirInfo.GetDirectories()) { ClearDir(di, ref DirCount, ref FileCount); di.Attributes = FileAttributes.Normal; di.Delete(); DirCount++; } } /// /// 清理目录 /// /// 目录信息 /// 排除文件列表(文件名为小写且不包启路径) /// 清理目录数(用于返回) /// 清理文件数(用于返回) static void ClearDir(DirectoryInfo DirInfo, HashSet ExcludeFiles, ref int DirCount, ref int FileCount) { foreach (FileInfo fi in DirInfo.GetFiles()) { if (ExcludeFiles.Contains(fi.Name.ToLower())) { continue; } fi.Attributes = FileAttributes.Normal; fi.Delete(); FileCount++; } foreach (DirectoryInfo di in DirInfo.GetDirectories()) { ClearDir(di, ExcludeFiles, ref DirCount, ref FileCount); di.Attributes = FileAttributes.Normal; di.Delete(); DirCount++; } } #endregion #region 删除文件夹(包含子文件夹及文件) /// /// 删除文件夹(包含子文件夹及文件) /// /// 目录 /// 排除文件列表(文件名为小写且不包启路径) /// 文件数量 public static int DelDir(string Dir, HashSet ExcludeFiles = null) { return DelDir(new DirectoryInfo(Dir), ExcludeFiles); } /// /// 删除文件夹 /// /// 目录信息 /// 排除文件列表(文件名为小写且不包启路径) /// 文件数量 public static int DelDir(DirectoryInfo DirInfo, HashSet ExcludeFiles = null) { var count = ClearDir(DirInfo, ExcludeFiles); if (DirInfo.Exists) { DirInfo.Delete(); } return count; } /// /// 删除空文件夹 /// /// 目录信息 /// 删除目录数 public static int DelEmptyDir(DirectoryInfo DirInfo) { if (!DirInfo.Exists) { return 0; } int DirCount = 0; DelEmptyDir(DirInfo, ref DirCount); return DirCount; } /// /// 删除空文件夹 /// /// 目录信息 /// 删除目录数(用于返回) static void DelEmptyDir(DirectoryInfo DirInfo, ref int DirCount) { foreach (DirectoryInfo di in DirInfo.GetDirectories()) { DelEmptyDir(di, ref DirCount); } if ((DirInfo.GetDirectories().Count() == 0) && (DirInfo.GetFiles().Count() == 0)) { DirInfo.Attributes = FileAttributes.Normal; DirInfo.Delete(); DirCount++; } } #endregion #region 文件Md5校验码 /// /// 获取文件Md5校验码 /// /// /// public static string GetFileMd5Value(string File) { if (!System.IO.File.Exists(File)) { return string.Empty; } Stream inputStream = System.IO.File.Open(File, FileMode.Open, FileAccess.Read, FileShare.Read); string md5 = GetFileMd5Value(inputStream, true); return md5; } /// /// 获取文件Md5校验码 /// /// /// /// public static string GetFileMd5Value(Stream FileStream, bool IsCloseStream = true) { int bufferSize = 1024 * 16;//自定义缓冲区大小16K byte[] buffer = new byte[bufferSize]; HashAlgorithm hashAlgorithm = new MD5CryptoServiceProvider(); int readLength = 0;//每次读取长度 var output = new byte[bufferSize]; while ((readLength = FileStream.Read(buffer, 0, buffer.Length)) > 0) { //计算MD5 hashAlgorithm.TransformBlock(buffer, 0, readLength, output, 0); } //完成最后计算,必须调用(由于上一部循环已经完成所有运算,所以调用此方法时后面的两个参数都为0) hashAlgorithm.TransformFinalBlock(buffer, 0, 0); string md5 = BitConverter.ToString(hashAlgorithm.Hash); hashAlgorithm.Clear(); if (IsCloseStream) { FileStream.Close(); } md5 = md5.Replace("-", ""); return md5; } /// /// 获取文件MD5值 /// add by sunyichao 2019-01-08 /// /// 文件路径 /// public static string GetMD5HashFromFile(string fileName) { try { FileStream file = new FileStream(fileName, FileMode.Open); System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(file); file.Close(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString("x2")); } return sb.ToString(); } catch (Exception ex) { throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message); } } #endregion /// /// 在指定的服务器路径添加存储文件[会覆盖同路径下同名文件] /// /// 获得的上传文件HttpPostedFile /// 服务器的存储路径 /// 存储文件的文件名 /// true=上传成功 public static bool UpFiles(HttpPostedFileBase getFiles, string path, string fileName) { path = HttpContext.Current.Server.MapPath(path); //文件夹不存在的时候,创建文件夹 if (!Directory.Exists(path)) Directory.CreateDirectory(path); string fullName = path + fileName; FileInfo fileInfo = new FileInfo(fullName); if (fileInfo.Exists) return false; getFiles.SaveAs(fullName); return true; } /// /// 大文件分割 /// /// 待分割文件路径:如:D:\x_20160407.txt /// 当文件大于这个配置项时就执行文件分隔:单位M /// 每个分隔出来的文件大小:单位M /// 新分割出的文件格式:如D:\x_20160407{0}.txt /// public static int SplitFile(string filepath, int splitMinFileSize, int splitFileSize, string splitFileFormat) { string file = filepath; FileInfo fileInfo = new FileInfo(file); if (fileInfo.Length > splitMinFileSize) { // Console.WriteLine("判定结果:需要分隔文件!"); } else { //Console.WriteLine("判定结果:不需要分隔文件!"); //Console.ReadKey(); return 0; } int steps = Math.Ceiling(fileInfo.Length / (splitFileSize * 1.0)).ToInt2(); using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read)) { using (BinaryReader br = new BinaryReader(fs)) { int couter = 1; bool isReadingComplete = false; while (!isReadingComplete) { string filePath = string.Format(splitFileFormat, couter); // Console.WriteLine("开始读取文件【{1}】:{0}", filePath, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")); byte[] input = br.ReadBytes(splitFileSize); //能否读取到指定长度的字节 if (input.Length >= splitFileSize) { using (FileStream writeFs = new FileStream(filePath, FileMode.Create)) { using (BinaryWriter bw = new BinaryWriter(writeFs)) { bw.Write(input); } } } else { isReadingComplete = (input.Length < splitFileSize); } if (!isReadingComplete) { couter += 1; } // Console.WriteLine("完成读取文件【{1}】:{0}", filePath, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")); } } } if (fileInfo.Length >= splitFileSize) fileInfo.Delete(); return 0; } } }