using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web; namespace FTP.Models { public class FilesHelper { public Dictionary directorys = new Dictionary(); public List lists = new List(); OperationResult operation = new OperationResult(); public int count = 1; public string counts; bool flag; #region 递归获取Windows目录下的文件和文件夹,返回一个元组 /// /// 递归获取Windows目录下的文件和文件夹 /// /// 文件绝对路径 /// public Tuple, Dictionary> GetDirectoryAndFile(string sourcePath) { GetDirectory(sourcePath); if (lists.Count > 0) { operation.isOk = true; operation.returnValue = "获取递归文件夹和文件列表成功"; return new Tuple, Dictionary>(operation, lists, directorys); } operation.isOk = false; operation.returnValue = "获取递归文件夹和文件列表失败"; return new Tuple, Dictionary>(operation, lists, directorys); } /// /// 递归获取Windows目录下的文件和文件夹 /// /// 文件绝对路径 private void GetDirectory(string sourcePath) { try { //判断源文件夹是否存在 if (Directory.Exists(sourcePath)) { //获取源文件夹中的目录及文件路径,存入字符串 string[] tmp = Directory.GetFileSystemEntries(sourcePath); //循环遍历 for (int i = 0; i < tmp.Length; i++) { //如果是文件则存入FileList if (File.Exists(tmp[i])) { counts = (++count).ToString(); lists.Add(sourcePath); directorys.Add(counts, tmp[i]); } else { GetDirectory(tmp[i]); } } } } catch (Exception ex) { return; } } #endregion //#region 工具方法:ASP.NET上传文件的方法 ///// ///// 工具方法:上传文件的方法 ///// ///// 上传控件的ID ///// 允许上传的扩展文件名类型,如:string[] allowExtensions = { ".doc", ".xls", ".ppt", ".jpg", ".gif" }; ///// 允许上传的最大大小,以M为单位 ///// 保存文件的目录,注意是绝对路径,如:Server.MapPath("~/upload/"); ///// 保存的文件名,如果是""则以原文件名保存 //public OperationResult FilesUpload(FileUpload myFileUpload, string[] allowExtensions, int maxLength, string savePath, string saveName) //{ // //文件格式是否允许上传 // bool fileAllow = false; // //检查是否有文件案 // if (myFileUpload.HasFile) // { // //检查文件大小, ContentLength获取的是字节,转成M的时候要除以2次1024 // if (myFileUpload.PostedFile.ContentLength / 1024 / 1024 >= maxLength) // { // operation.isOk = false; // operation.tRes = "只能上传小于" + maxLength.ToString() + "的文件!"; // return operation; // } // //取得上传文件之扩展文件名,并转换成小写字母 // string fileExtension = System.IO.Path.GetExtension(myFileUpload.FileName).ToLower(); // string tmp = ""; // 存储允许上传的文件后缀名 // //检查扩展文件名是否符合限定类型 // for (int i = 0; i < allowExtensions.Length; i++) // { // tmp += i == allowExtensions.Length - 1 ? allowExtensions[i] : allowExtensions[i] + ","; // if (fileExtension == allowExtensions[i]) // { // fileAllow = true; // } // } // if (fileAllow) // { // try // { // string path = savePath + (saveName == "" ? myFileUpload.FileName : saveName); // //存储文件到文件夹 // myFileUpload.SaveAs(path); // } // catch (Exception ex) // { // operation.isOk = false; // operation.tRes = "文件上传错误,错误原因:" + ex.ToString(); // return operation; // } // } // else // { // operation.isOk = false; // operation.tRes = "文件格式不符,可以上传的文件格式为:" + tmp; // return operation; // } // } // else // { // operation.isOk = false; // operation.tRes = "请选择要上传的文件!"; // return operation; // } // operation.isOk = true; // operation.tRes = "文件上传成功!"; // return operation; //} //#endregion #region 返回文件是否存在 /// /// 返回文件是否存在 /// /// 文件地址 /// 是否存在 public OperationResult FileExists(string SouthPath) { flag = System.IO.File.Exists(SouthPath); if (flag) { operation.tRes = "文件存在!"; } else { operation.tRes = "文件不存在!"; } operation.isOk = flag; return operation; } #endregion #region 判断文件名是否为浏览器可以直接显示的图片文件名 /// /// 判断文件名是否为浏览器可以直接显示的图片文件名 /// /// 文件名 /// 是否可以直接显示 public OperationResult IsImgFilename(string filename) { filename = filename.Trim(); if (filename.EndsWith(".") || filename.IndexOf(".") == -1) { operation.isOk = false; operation.tRes = "文件不可以直接显示!"; return operation; } string extname = filename.Substring(filename.LastIndexOf(".") + 1).ToLower(); flag = (extname == "jpg" || extname == "jpeg" || extname == "png" || extname == "bmp" || extname == "gif"); if (flag) { operation.tRes = "文件可以直接显示!"; } operation.isOk = flag; operation.tRes = "文件不可以直接显示!"; return operation; } #endregion #region 复制当前目录的所有文件 /// /// 复制当前目录的所有文件 /// /// 原始目录 /// 目标目录 /// 如果为true,覆盖同名文件,否则不覆盖 /// 如果为true,包含子目录,否则不包含 public OperationResult CopyAllFiles(string sourceDir, string targetDir, bool overWrite, bool copySubDir) { //目录不存在首先创建目录 if (!Directory.Exists(targetDir)) { Directory.CreateDirectory(targetDir); } try { //辅助当前目录文件 foreach (string sourceFileName in Directory.GetFiles(sourceDir)) { string targetFileName = Path.Combine(targetDir, sourceFileName.Substring(sourceFileName.LastIndexOf('\\') + 1)); if (File.Exists(targetFileName)) { if (overWrite == true) { File.SetAttributes(targetFileName, FileAttributes.Normal); File.Copy(sourceFileName, targetFileName, overWrite); } } else { File.Copy(sourceFileName, targetFileName, overWrite); } } if (copySubDir) { foreach (string sourceSubDir in Directory.GetDirectories(sourceDir)) { string targetSubDir = Path.Combine(targetDir, sourceSubDir.Substring(sourceSubDir.LastIndexOf('\\') + 1)); if (!Directory.Exists(targetSubDir)) { Directory.CreateDirectory(targetSubDir); } CopyAllFiles(sourceSubDir, targetSubDir, overWrite, true); } } operation.isOk = true; operation.returnValue = string.Format("复制目录 {0}的文件到目录 {1}成功,总计复制{2}个文件!", sourceDir, targetDir, count.ToString()); } catch (Exception ex) { operation.isOk = false; operation.returnValue = string.Format("复制目录 {0}的文件到目录 {1}失败,失败原因:{3}!", sourceDir, targetDir, ex.ToString()); } return operation; } #endregion #region 剪切/移动指定目录的所有文件 /// /// 移动当前目录的文件 /// /// 原始目录 /// 目标目录 /// 如果为true,覆盖同名文件,否则不覆盖 /// 如果为true,包含目录,否则不包含 public OperationResult MoveFiles(string sourceDir, string targetDir, bool overWrite, bool moveSubDir) { //目录不存在首先创建目录 if (!Directory.Exists(targetDir)) { Directory.CreateDirectory(targetDir); } try { //移动当前目录文件 foreach (string sourceFileName in Directory.GetFiles(sourceDir)) { string targetFileName = Path.Combine(targetDir, sourceFileName.Substring(sourceFileName.LastIndexOf('\\') + 1)); if (File.Exists(targetFileName)) { if (overWrite == true) { File.SetAttributes(targetFileName, FileAttributes.Normal); File.Delete(targetFileName); File.Move(sourceFileName, targetFileName); } } else { File.Move(sourceFileName, targetFileName); } } if (moveSubDir) { foreach (string sourceSubDir in Directory.GetDirectories(sourceDir)) { string targetSubDir = Path.Combine(targetDir, sourceSubDir.Substring(sourceSubDir.LastIndexOf('\\') + 1)); if (!Directory.Exists(targetSubDir)) { Directory.CreateDirectory(targetSubDir); } MoveFiles(sourceSubDir, targetSubDir, overWrite, true); Directory.Delete(sourceSubDir); } } operation.isOk = true; operation.returnValue = string.Format("移动目录 {0}的所有文件到目录 {1}成功!", sourceDir, targetDir); } catch (Exception ex) { operation.isOk = false; operation.returnValue = string.Format("移动目录 {0}的所有文件到目录 {1}失败,失败原因:{3}!", sourceDir, targetDir, ex.ToString()); } return operation; } #endregion #region 删除指定目录的所有文件和子目录 /// /// 删除指定目录的所有文件和子目录 /// /// 操作目录 /// 如果为true,包含对子目录的操作 public OperationResult DeleteDirectoryFiles(string TargetDir, bool delSubDir) { //判断目录是否存在 flag = Directory.Exists(TargetDir); try { if (flag) { foreach (string fileName in Directory.GetFiles(TargetDir)) { File.SetAttributes(fileName, FileAttributes.Normal); File.Delete(fileName); } if (delSubDir) { DirectoryInfo dir = new DirectoryInfo(TargetDir); foreach (DirectoryInfo subDi in dir.GetDirectories()) { DeleteDirectoryFiles(subDi.FullName, true); subDi.Delete(); } } operation.returnValue = string.Format("删除目录 {0} 下的文件成功", TargetDir); } } catch (Exception ex) { operation.returnValue = string.Format("删除目录 {0} 下的文件失败", TargetDir); } operation.isOk = flag; return operation; } #endregion #region 删除指定目录下的指定文件 /// /// 删除文件 /// /// 文件路径 public OperationResult DeleteFiles(string sourcePath) { //判断目录是否存在 flag = File.Exists(sourcePath); try { if (flag) { File.Delete(sourcePath); } operation.isOk = true; operation.returnValue = string.Format("删除路径 {0} 下的文件成功", sourcePath); } catch (Exception ex) { operation.isOk = false; operation.returnValue = string.Format("删除路径 {0} 下的文件失败,失败原因:{1}", sourcePath, ex.ToString()); } return operation; } #endregion #region 创建指定目录 /// /// 创建指定目录 /// /// public OperationResult CreateDirectory(string targetDir) { DirectoryInfo dir = new DirectoryInfo(targetDir); flag = dir.Exists; try { if (!flag) { dir.Create(); } operation.isOk = !flag; operation.returnValue = string.Format("创建指定目录{0}成功", targetDir); } catch (Exception ex) { operation.isOk = false; operation.returnValue = string.Format("创建指定目录{0}失败,失败原因{1}", targetDir, ex.ToString()); } return operation; } #endregion #region 建立子目录 /// /// 建立子目录 /// /// 目录路径 /// 子目录名称 public OperationResult CreateChildDirectory(string parentDir, string subDirName) { string path = parentDir + "\\" + subDirName; return CreateDirectory(path); } #endregion #region 重命名文件夹 /// /// 重命名文件夹 /// /// 原路径文件夹名称 /// 新路径文件夹名称 /// public bool ReNameFloder(string OldFloderName, string NewFloderName) { try { if (Directory.Exists(OldFloderName)) { Directory.Move(OldFloderName, NewFloderName); } return true; } catch { return false; } } #endregion #region 删除指定目录 /// /// 删除指定目录 /// /// 目录路径 public OperationResult DeleteDirectory(string targetDir) { DirectoryInfo dirInfo = new DirectoryInfo(targetDir); if (dirInfo.Exists) { return DeleteDirectoryFiles(targetDir, true); } operation.isOk = false; operation.returnValue = string.Format("目录{0}不存在", targetDir); return operation; } #endregion #region 检测目录是否存在 /// /// 检测目录是否存在 /// /// 路径 /// public bool DirectoryIsExists(string StrPath) { DirectoryInfo dirInfo = new DirectoryInfo(StrPath); return dirInfo.Exists; } /// /// 检测目录是否存在 /// /// 路径 /// 如果不存在,是否创建 public void DirectoryIsExists(string StrPath, bool Create) { DirectoryInfo dirInfo = new DirectoryInfo(StrPath); flag = DirectoryIsExists(StrPath); if (!flag) { if (Create) { dirInfo.Create(); } } } #endregion #region 删除指定目录的所有子目录,不包括对当前目录文件的删除 /// /// 删除指定目录的所有子目录,不包括对当前目录文件的删除 /// /// 目录路径 public OperationResult DeleteSubDirectory(string targetDir) { flag = DirectoryIsExists(targetDir); if (flag) { foreach (string subDir in Directory.GetDirectories(targetDir)) { DeleteDirectory(subDir); } operation.returnValue = string.Format("删除目录{0}下的所有子目录成功", targetDir); } operation.isOk = flag; operation.returnValue = string.Format("目录{0}不存在", targetDir); return operation; } #endregion #region 获取文件最后修改时间 /// /// 获取文件最后修改时间 /// /// 文件真实路径 /// public DateTime GetFileWriteTime(string FileUrl) { return File.GetLastWriteTime(FileUrl); } #endregion #region 重命名文件 /// /// 重命名文件 /// /// 旧文件真实路径 /// 新文件真实路径 /// public OperationResult RenameFile(string OldFileName, string NewFileName) { flag = File.Exists(OldFileName); if (flag) { File.Move(OldFileName, NewFileName); operation.isOk = flag; operation.returnValue = string.Format("旧文件{0}重命名为新文件{1}成功", OldFileName, NewFileName); return operation; } operation.isOk = flag; operation.returnValue = string.Format("旧文件{0}不存在", OldFileName); return operation; } #endregion #region 返回指定路径的文件的扩展名 /// /// 返回指定路径的文件的扩展名 /// /// 完整路径的文件 /// public string GetFileExtension(string PathFileName) { return Path.GetExtension(PathFileName); } #endregion #region 判断是否是隐藏文件 /// /// 判断是否是隐藏文件 /// /// 文件路径 /// public bool IsHiddenFile(string path) { FileAttributes MyAttributes = File.GetAttributes(path); string MyFileType = MyAttributes.ToString(); if (MyFileType.LastIndexOf("Hidden") != -1) //是否隐藏文件 { return true; } return false; } #endregion #region 以只读方式读取文本文件 /// /// 以只读方式读取文本文件 /// /// 文件路径及文件名 /// public string ReadTxtFile(string FilePath) { flag = File.Exists(FilePath); string content = "";//返回的字符串 if (flag) { using (FileStream fs = new FileStream(FilePath, FileMode.Open)) { using (StreamReader reader = new StreamReader(fs, Encoding.UTF8)) { string text = string.Empty; while (!reader.EndOfStream) { text += reader.ReadLine() + "\r\n"; content = text; } } } } return content; } #endregion #region 将内容写入文本文件(如果文件path存在就打开,不存在就新建) /// /// 将内容写入文本文件(如果文件path存在就打开,不存在就新建) /// /// 文件路径 /// 要写入的内容 /// 写入模式:append 是追加写, CreateNew 是覆盖 public OperationResult WriteStrToTxtFile(string FilePath, string WriteStr, FileMode FileModes) { flag = File.Exists(FilePath); operation.isOk = flag; if (flag) { FileStream fst = new FileStream(FilePath, FileModes); StreamWriter swt = new StreamWriter(fst, Encoding.GetEncoding("utf-8")); swt.WriteLine(WriteStr); swt.Close(); fst.Close(); operation.returnValue = string.Format("写入为文件{0}数据成功", FilePath); return operation; } operation.returnValue = string.Format("文件{0}不存在", FilePath); return operation; } #endregion #region 获取本地驱动器名列表 /// /// 获取本地驱动器名列表 /// /// public static string[] GetLocalDrives() { return Directory.GetLogicalDrives(); } #endregion #region 获取应用程序当前可执行文件的路径 /// /// 获取应用程序当前可执行文件的路径 /// /// public static string GetAppCurrentDirectory() { //return Application.StartupPath; return null; } #endregion #region 获取文件大小并以B,KB,GB,TB方式表示[+2 重载] /// /// 获取文件大小并以B,KB,GB,TB方式表示 /// /// 文件(FileInfo类型) /// public static string GetFileSize(FileInfo File) { string Result = ""; long FileSize = File.Length; if (FileSize >= 1024 * 1024 * 1024) { if (FileSize / 1024 * 1024 * 1024 * 1024 >= 1024) Result = string.Format("{0:############0.00} TB", (double)FileSize / 1024 * 1024 * 1024 * 1024); else Result = string.Format("{0:####0.00} GB", (double)FileSize / 1024 * 1024 * 1024); } else if (FileSize >= 1024 * 1024) Result = string.Format("{0:####0.00} MB", (double)FileSize / 1024 * 1024); else if (FileSize >= 1024) Result = string.Format("{0:####0.00} KB", (double)FileSize / 1024); else Result = string.Format("{0:####0.00} Bytes", FileSize); return Result; } /// /// 获取文件大小并以B,KB,GB,TB方式表示 /// /// 文件的具体路径 /// public static string GetFileSize(string FilePath) { string Result = ""; FileInfo File = new FileInfo(FilePath); long FileSize = File.Length; if (FileSize >= 1024 * 1024 * 1024) { if (FileSize / 1024 * 1024 * 1024 * 1024 >= 1024) Result = string.Format("{0:########0.00} TB", (double)FileSize / 1024 * 1024 * 1024 * 1024); else Result = string.Format("{0:####0.00} GB", (double)FileSize / 1024 * 1024 * 1024); } else if (FileSize >= 1024 * 1024) Result = string.Format("{0:####0.00} MB", (double)FileSize / 1024 * 1024); else if (FileSize >= 1024) Result = string.Format("{0:####0.00} KB", (double)FileSize / 1024); else Result = string.Format("{0:####0.00} Bytes", FileSize); return Result; } #endregion //#region Http下载文件 ///// ///// 下载文件 ///// ///// 下载文件下载的完整路径及名称 //public void DownLoadFiles(string FileFullPath) //{ // if (!string.IsNullOrEmpty(FileFullPath) && (FileExists(FileFullPath)).isOk) // { // FileInfo fi = new FileInfo(FileFullPath); //文件信息 // FileFullPath = HttpUtility.UrlEncode(FileFullPath); //对文件名编码 // FileFullPath = FileFullPath.Replace("+", "%20"); //解决空格被编码为"+"号的问题 // HttpContext.Current.Response.Clear(); // HttpContext.Current.Response.ContentType = "application/octet-stream"; // HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileFullPath); // HttpContext.Current.Response.AppendHeader("content-length", fi.Length.ToString()); //文件长度 // int chunkSize = 102400; //缓存区大小,可根据服务器性能及网络情况进行修改 // byte[] buffer = new byte[chunkSize]; //缓存区 // using (FileStream fs = fi.Open(FileMode.Open)) //打开一个文件流 // { // //如果没到文件尾并且客户在线 // while (fs.Position >= 0 && HttpContext.Current.Response.IsClientConnected) // { // int tmp = fs.Read(buffer, 0, chunkSize); //读取一块文件 // if (tmp <= 0) break; //tmp=0说明文件已经读取完毕,则跳出循环 // HttpContext.Current.Response.OutputStream.Write(buffer, 0, tmp);//向客户端传送一块文件 // HttpContext.Current.Response.Flush();//保证缓存全部送出 // Thread.Sleep(10); //主线程休息一下,以释放CPU // } // } // } //} //#endregion } }