using Common.Extensions; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace Common.Helpers { /// /// 文件操作帮助类 /// public class FileHelper { private static object _filePathObj = new object(); /// /// 通过迭代器读取平面文件行内容(必须是带有\r\n换行的文件,百万行以上的内容读取效率存在问题,适用于100M左右文件,行100W内,超出的会有卡顿) /// /// 文件全路径 /// 分页页数 /// 分页大小 /// 是否最后一行向前读取,默认从前向后读取 /// public static IEnumerable ReadPageLine(string fullPath, int page, int pageSize, bool seekEnd = false) { if (page <= 0) { page = 1; } fullPath = StringExtension.ReplacePath(fullPath); var lines = File.ReadLines(fullPath, Encoding.UTF8); if (seekEnd) { int lineCount = lines.Count(); int linPageCount = (int)Math.Ceiling(lineCount / (pageSize * 1.00)); //超过总页数,不处理 if (page > linPageCount) { page = 0; pageSize = 0; } else if (page == linPageCount)//最后一页,取最后一页剩下所有的行 { pageSize = lineCount - (page - 1) * pageSize; if (page == 1) { page = 0; } else { page = lines.Count() - page * pageSize; } } else { page = lines.Count() - page * pageSize; } } else { page = (page - 1) * pageSize; } lines = lines.Skip(page).Take(pageSize); var enumerator = lines.GetEnumerator(); int count = 1; while (enumerator.MoveNext() || count <= pageSize) { yield return enumerator.Current; count++; } enumerator.Dispose(); } public static bool FileExists(string path) { return File.Exists(StringExtension.ReplacePath(path)); } public static string GetCurrentDownLoadPath() { return ("Download\\").MapPath(); } public static bool DirectoryExists(string path) { return Directory.Exists(StringExtension.ReplacePath(path)); } public static string Read_File(string fullpath, string filename, string suffix) { return ReadFile((fullpath + "\\" + filename + suffix).MapPath()); } public static string ReadFile(string fullName) { // Encoding code = Encoding.GetEncoding(); //Encoding.GetEncoding("gb2312"); string temp = fullName.MapPath().ReplacePath(); string str = ""; if (!File.Exists(temp)) { return str; } StreamReader sr = null; try { sr = new StreamReader(temp); str = sr.ReadToEnd(); // 读取文件 } catch { } sr?.Close(); sr?.Dispose(); return str; } /// /// 取后缀名 /// /// 文件名 /// .gif|.html格式 public static string GetPostfixStr(string filename) { int start = filename.LastIndexOf("."); int length = filename.Length; string postfix = filename.Substring(start, length - start); return postfix; } /// /// /// /// 路径 /// 文件名 /// 写入的内容 /// 是否将内容添加到未尾,默认不添加 public static void WriteFile(string path, string fileName, string content, bool appendToLast = false) { path = StringExtension.ReplacePath(path); fileName = StringExtension.ReplacePath(fileName); if (!Directory.Exists(path))//如果不存在就创建file文件夹 Directory.CreateDirectory(path); using (FileStream stream = File.Open(Path.Combine(path, fileName), FileMode.OpenOrCreate, FileAccess.Write)) { byte[] by = Encoding.Default.GetBytes(content); if (appendToLast) { stream.Position = stream.Length; } else { stream.SetLength(0); } stream.Write(by, 0, by.Length); } } /// /// 追加文件 /// /// 文件路径 /// 内容 public static void FileAdd(string Path, string strings) { StreamWriter sw = File.AppendText(StringExtension.ReplacePath(Path)); sw.Write(strings); sw.Flush(); sw.Close(); sw.Dispose(); } /// /// 拷贝文件 /// /// 原始文件 /// 新文件路径 public static void FileCoppy(string OrignFile, string NewFile) { File.Copy(StringExtension.ReplacePath(OrignFile), StringExtension.ReplacePath(NewFile), true); } /// /// 删除文件 /// /// 路径 public static void FileDel(string Path) { File.Delete(StringExtension.ReplacePath(Path)); } /// /// 移动文件 /// /// 原始路径 /// 新路径 public static void FileMove(string OrignFile, string NewFile) { File.Move(StringExtension.ReplacePath(OrignFile), StringExtension.ReplacePath(NewFile)); } /// /// 在当前目录下创建目录 /// /// 当前目录 /// 新目录 public static void FolderCreate(string OrignFolder, string NewFloder) { Directory.SetCurrentDirectory(StringExtension.ReplacePath(OrignFolder)); Directory.CreateDirectory(StringExtension.ReplacePath(NewFloder)); } /// /// 创建文件夹 /// /// public static void FolderCreate(string Path) { // 判断目标目录是否存在如果不存在则新建之 if (!Directory.Exists(StringExtension.ReplacePath(Path))) Directory.CreateDirectory(StringExtension.ReplacePath(Path)); } public static void FileCreate(string Path) { FileInfo CreateFile = new FileInfo(StringExtension.ReplacePath(Path)); //创建文件 if (!CreateFile.Exists) { FileStream FS = CreateFile.Create(); FS.Close(); } } /// /// 递归删除文件夹目录及文件 /// /// /// public static void DeleteFolder(string dir) { dir = StringExtension.ReplacePath(dir); if (Directory.Exists(dir)) //如果存在这个文件夹删除之 { foreach (string d in Directory.GetFileSystemEntries(dir)) { if (File.Exists(d)) File.Delete(d); //直接删除其中的文件 else DeleteFolder(d); //递归删除子文件夹 } Directory.Delete(dir, true); //删除已空文件夹 } } /// /// 指定文件夹下面的所有内容copy到目标文件夹下面 /// /// 原始路径 /// 目标文件夹 public static void CopyDir(string srcPath, string aimPath) { try { aimPath = StringExtension.ReplacePath(aimPath); // 检查目标目录是否以目录分割字符结束如果不是则添加之 if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar) aimPath += Path.DirectorySeparatorChar; // 判断目标目录是否存在如果不存在则新建之 if (!Directory.Exists(aimPath)) Directory.CreateDirectory(aimPath); // 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组 //如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法 //string[] fileList = Directory.GetFiles(srcPath); string[] fileList = Directory.GetFileSystemEntries(StringExtension.ReplacePath(srcPath)); //遍历所有的文件和目录 foreach (string file in fileList) { //先当作目录处理如果存在这个目录就递归Copy该目录下面的文件 if (Directory.Exists(file)) CopyDir(file, aimPath + Path.GetFileName(file)); //否则直接Copy文件 else File.Copy(file, aimPath + Path.GetFileName(file), true); } } catch (Exception ee) { throw new Exception(ee.ToString()); } } /// /// 获取文件夹大小 /// /// 文件夹路径 /// public static long GetDirectoryLength(string dirPath) { dirPath = StringExtension.ReplacePath(dirPath); if (!Directory.Exists(dirPath)) return 0; long len = 0; DirectoryInfo di = new DirectoryInfo(dirPath); foreach (FileInfo fi in di.GetFiles()) { len += fi.Length; } DirectoryInfo[] dis = di.GetDirectories(); if (dis.Length > 0) { for (int i = 0; i < dis.Length; i++) { len += GetDirectoryLength(dis[i].FullName); } } return len; } /// /// 获取指定文件详细属性 /// /// 文件详细路径 /// public static string GetFileAttibe(string filePath) { string str = ""; filePath = StringExtension.ReplacePath(filePath); System.IO.FileInfo objFI = new System.IO.FileInfo(filePath); str += "详细路径:" + objFI.FullName + "
文件名称:" + objFI.Name + "
文件长度:" + objFI.Length.ToString() + "字节
创建时间" + objFI.CreationTime.ToString() + "
最后访问时间:" + objFI.LastAccessTime.ToString() + "
修改时间:" + objFI.LastWriteTime.ToString() + "
所在目录:" + objFI.DirectoryName + "
扩展名:" + objFI.Extension; return str; } /// /// 括号匹配算法 /// /// 原始字符串 /// 左匹配符号 /// 右匹配符号 /// private static string parenthesisMatch(string dataStr, char leftCode, char rightCode) { Stack stack = new Stack(); string cut_text = ""; for (int i = 0; i < dataStr.Length; ++i) { char ch = dataStr[i]; if (stack.Count > 0) { cut_text += ch; } if (ch == leftCode) { stack.Push(ch); } if (ch == rightCode) { stack.Pop(); if (0 == stack.Count) { return cut_text.Substring(0, cut_text.Length - 1); } } } return ""; } /// /// 替换内容(正则 + 括号匹配算法) /// /// 文件路径 /// 追加内容 public static void RegxAddContentByParenthesis(string path, string addStr) { path = StringExtension.ReplacePath(path); FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); StreamReader sr = new StreamReader(fs); string originStr = sr.ReadToEnd(); string pattern = @"DbContext\s*?({.*)"; if (Regex.IsMatch(originStr, pattern)) { Match match = Regex.Match(originStr, pattern, RegexOptions.Singleline); string cut_str = parenthesisMatch(match.Groups[1].Value, '{', '}'); // 剪切内容(原内容) string new_str = cut_str + "\r\n " + addStr + "\r\n"; // 实际更新内容 originStr = originStr.Replace(cut_str, new_str); } sr.Close(); fs.Close(); FileStream fs2 = new FileStream(path, FileMode.Open, FileAccess.Write); StreamWriter sw = new StreamWriter(fs2); sw.WriteLine(originStr); sw.Close(); fs2.Close(); } } }