使用实例:
private string urlPath = ""; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { urlPath = Server.MapPath("~/file/"); fileInfo(); } } /// <summary> /// 文件操作 /// </summary> private void fileInfo() { /*Response.Write("文件后缀:" + FileDownHelper.FileNameExtension("file/test.txt") + "<br />"); Response.Write("文件路径:" + FileDownHelper.MapPathFile("~/file/") + "<br />"); #region 下载文件 FileDownHelper.DownLoadold("file/test.txt"); FileDownHelper.DownLoad("file/eclipse.zip"); FileDownHelper.ResponseFile(Request, Response, "eclipse_d.zip", urlPath + "eclipse.zip", 10000); //10000可以100K #endregion*/ #region 文件操作 if (FileHelper.IsExistFile(urlPath + "test.txt")) { Response.Write("文件test.txt已经存在<br />"); } else { Response.Write("文件test.txt不存在<br />"); } //FileHelper.ExistsFile(urlPath + "test.txt"); //文件不存在则创建 Response.Write("文件名:" + FileHelper.GetFileName("file/test.txt") + "<br />"); //FileHelper.CreateFile(urlPath + "test.txt"); string mS = "MD5加密字符串:4QrcOUm6Wau+VuBX8g+IPg==\r\nMD5_16加密字符串:49BA59ABBE56E057\r\nMD5_32加密字符串:e10adc3949ba59abbe56e057f20f883e\r\nMD5(哈希)加密字符串:4QrcOUm6Wau+VuBX8g+IPg==\r\nDES加密字符串:BFE89F1A08F228B4\r\nDES解密字符串:123456\r\nRSA加密字符串:ILWFODZ2M3t1yXHoYxI5g2JSFR7mHIC8XkjBldKpClX4Fd5Y4l1SBEdXSpMyLXNw4xcedJZPf1EWosPjnUPb7o2h+4uFAEYvKJOGC6RaSre7eYVfGHKFJ76tvCZ+7qM26BEvhVOTpLKqn54URwg5cJg/YA9ANiGKbodBX2JnE7k=\r\nRSA解密字符串:123456\r\nAES加密字符串:VAsFoVM6j7jx1z3VKwZ0OA==\r\nAES解密字符串:123456\r\nDES(哈希)加密字符串:71FAFEBAAC484451\r\nDES(哈希)解密字符串:123456\r\nBase64加密字符串:MTIzNDU2\r\nBase64解密字符串:123456"; //FileHelper.CreateFile(urlPath + "test.txt", mS); //byte[] b = Encoding.Default.GetBytes(mS + "\r\n测试"); //FileHelper.CreateFile(urlPath + "test.txt", b); FileHelper.WriteText(urlPath + "test.txt", mS + "\r\n测试" + "\r\n测试", Encoding.Default); FileHelper.AppendText(urlPath + "test.txt", "\r\n" + mS, Encoding.Default); //FileHelper.Copy(urlPath + "test.txt", urlPath + "test/test.txt"); //FileHelper.Copy(urlPath + "test.txt", urlPath + "test/test1.txt"); //FileHelper.Move(urlPath + "test.txt", urlPath + "test/"); //FileHelper.DeleteFile(urlPath + "test/" + "test.txt"); //FileHelper.MoveFile(urlPath + "test.txt", urlPath + "test/test1.txt"); //FileHelper.CopyFile(urlPath + "test.txt", urlPath + "test/"); //FileHelper.ClearFile(urlPath + "test.txt"); Response.Write("文件行数:" + FileHelper.GetLineCount(urlPath + "test.txt") + "<br />"); Response.Write("文件大小:" + FileHelper.GetFileSize(urlPath + "test.txt", false) + "<br />"); Response.Write("文件名称:" + FileHelper.GetFileNameNoExtension(urlPath + "test.txt") + "<br />"); Response.Write("文件后缀:" + FileHelper.GetExtension(urlPath + "test.txt") + "<br />"); //FileHelper.CopyFolder(urlPath + "test", urlPath + "test1"); //FileHelper.DeleteFolderFiles(urlPath + "test", urlPath + "test1"); if (FileHelper.IsEmptyDirectory(urlPath + "test1/")) { Response.Write("文件夹test1是空目录<br />"); } else { Response.Write("文件夹test1是非空目录<br />"); } if (FileHelper.IsExistDirectory(urlPath + "test1/")) { Response.Write("文件夹test1已经存在<br />"); } else { Response.Write("文件夹test1不存在<br />"); } if (FileHelper.Contains(urlPath + "test/", "test1.txt")) { Response.Write("文件夹test下存在test1.txt文件<br />"); } else { Response.Write("文件夹test下不存在test1.txt文件<br />"); } if (FileHelper.Contains(urlPath + "test/", "test1.txt", true)) { Response.Write("文件夹test下能找到test1.txt文件<br />"); } else { Response.Write("文件夹test下不能找到test1.txt文件<br />"); } FileHelper.CreateDir(urlPath + "test2/"); FileHelper.CreateDirectory(urlPath + "test2/test3/"); FileHelper.CreateDirectory(urlPath + "test3/"); FileHelper.DeleteDir(urlPath + "test3/"); //FileHelper.ClearDirectory(urlPath + "test2/"); //FileHelper.DeleteDirectory(urlPath + "test2/"); string[] fD = FileHelper.GetDirectories(urlPath + "test/"); string[] fF = FileHelper.GetFileNames(urlPath + "test/"); string[] fAF = FileHelper.GetFileNames(urlPath, "*.txt", true); Stream s = FileHelper.FileToStream(urlPath + "test.txt"); byte[] b = FileHelper.FileToBytes(urlPath + "test.txt"); FileHelper.StreamToFile(s, urlPath + "test3.txt"); byte[] bb = FileHelper.StreamToBytes(s); Stream ss = FileHelper.BytesToStream(b); FileHelper.UpLoadFile(b, urlPath + "test4.txt"); VerCodeHelper v = new VerCodeHelper(); string sBase = FileHelper.ImgToBase64String("zhengdecai"); string iBase = FileHelper.ImgToBase64String(v.Image); FileHelper.Base64ToImage(iBase, urlPath + "1.png"); byte[] bImage = FileHelper.ImageToByte(urlPath + "1.png"); byte[] bImg = FileHelper.ImgToByte(v.Image); System.Drawing.Image img = FileHelper.ByteToImg(bImg); Response.Write("文件夹:" + FileHelper.GetDictSize(urlPath) + "<br />"); string bBin = FileHelper.FileToBinary(urlPath + "test4.txt"); FileHelper.CreateDir(urlPath + "File/"); FileHelper.BinaryToFile(urlPath + "File/test4.txt", bBin); #endregion }
类库信息:
/// <summary> /// 文件下载类 /// </summary> public class FileDownHelper { #region 基础方法 /// <summary> /// 读取虚拟目录文件的文件后缀 /// </summary> /// <param name="fileName">文件虚拟路径</param> /// <returns></returns> public static string FileNameExtension(string fileName) { return Path.GetExtension(MapPathFile(fileName)); } /// <summary> /// 获取虚拟目录的物理地址 /// </summary> /// <param name="fileName">文件虚拟路径</param> /// <returns></returns> public static string MapPathFile(string fileName) { return HttpContext.Current.Server.MapPath(fileName); } #endregion #region 下载文件操作 /// <summary> /// 普通下载 /// </summary> /// <param name="fileName">文件虚拟路径</param> public static void DownLoadold(string fileName) { string destFileName = MapPathFile(fileName); if (File.Exists(destFileName)) { FileInfo fi = new FileInfo(destFileName); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ClearHeaders(); HttpContext.Current.Response.Buffer = false; HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(Path.GetFileName(destFileName), System.Text.Encoding.UTF8)); HttpContext.Current.Response.AppendHeader("Content-Length", fi.Length.ToString()); HttpContext.Current.Response.ContentType = "application/octet-stream"; HttpContext.Current.Response.WriteFile(destFileName); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.End(); } } /// <summary> /// 分块下载 /// </summary> /// <param name="fileName">文件虚拟路径</param> public static void DownLoad(string fileName) { string filePath = MapPathFile(fileName); long chunkSize = 204800; //指定块大小 byte[] buffer = new byte[chunkSize]; //建立一个200K的缓冲区 long dataToRead = 0; //已读的字节数 FileStream stream = null; try { //打开文件 stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); dataToRead = stream.Length; //添加Http头 HttpContext.Current.Response.ContentType = "application/octet-stream"; HttpContext.Current.Response.AddHeader("Content-Disposition", "attachement;filename=" + HttpUtility.UrlEncode(Path.GetFileName(filePath))); HttpContext.Current.Response.AddHeader("Content-Length", dataToRead.ToString()); while (dataToRead > 0) { if (HttpContext.Current.Response.IsClientConnected) { int length = stream.Read(buffer, 0, Convert.ToInt32(chunkSize)); HttpContext.Current.Response.OutputStream.Write(buffer, 0, length); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.Clear(); dataToRead -= length; } else { dataToRead = -1; //防止client失去连接 } } } catch (Exception ex) { HttpContext.Current.Response.Write("Error:" + ex.Message); } finally { if (stream != null) stream.Close(); HttpContext.Current.Response.Close(); } } /// <summary> /// 输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小 /// </summary> /// <param name="request">Page.Request对象</param> /// <param name="response">Page.Response对象</param> /// <param name="fileName">下载文件名</param> /// <param name="filePath">带文件名下载路径</param> /// <param name="speed">每秒允许下载的字节数</param> /// <returns>返回是否成功</returns> //--------------------------------------------------------------------- //调用: // string FullPath=Server.MapPath("count.txt"); // ResponseFile(this.Request,this.Response,"count.txt",FullPath,100); //--------------------------------------------------------------------- public static bool ResponseFile(HttpRequest request, HttpResponse response, string fileName, string filePath, long speed) { try { FileStream myFile = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); BinaryReader br = new BinaryReader(myFile); try { response.AddHeader("Accept-Ranges", "bytes"); response.Buffer = false; long fileLength = myFile.Length; long startBytes = 0; int pack = 10240; //10K bytes int sleep = (int)Math.Floor((double)(1000 * pack / speed)) + 1; if (request.Headers["Range"] != null) { response.StatusCode = 206; string[] range = request.Headers["Range"].Split(new char[] { '=', '-' }); startBytes = Convert.ToInt64(range[1]); } response.AddHeader("Content-Length", (fileLength - startBytes).ToString()); if (startBytes != 0) { response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength)); } response.AddHeader("Connection", "Keep-Alive"); response.ContentType = "application/octet-stream"; response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); br.BaseStream.Seek(startBytes, SeekOrigin.Begin); int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1; for (int i = 0; i < maxCount; i++) { if (response.IsClientConnected) { response.BinaryWrite(br.ReadBytes(pack)); Thread.Sleep(sleep); } else { i = maxCount; } } } catch { return false; } finally { br.Close(); myFile.Close(); } } catch { return false; } return true; } #endregion } /// <summary> /// 文件操作类 /// </summary> public class FileHelper { #region 文件操作 #region 文件检测操作 /// <summary> /// 检测指定文件是否存在,如果存在则返回true。 /// </summary> /// <param name="filePath">文件的绝对路径</param> public static bool IsExistFile(string filePath) { return File.Exists(filePath); } /// <summary> /// 检查文件,如果文件不存在则创建 /// </summary> /// <param name="FilePath">路径,包括文件名</param> public static void ExistsFile(string FilePath) { //if(!File.Exists(FilePath)) //File.Create(FilePath); //以上写法会报错,详细解释请看下文......... if (!File.Exists(FilePath)) { FileStream fs = File.Create(FilePath); fs.Close(); } } /// <summary> /// 从文件的绝对路径中获取文件名( 包含扩展名 ) /// </summary> /// <param name="filePath">文件的绝对路径</param> public static string GetFileName(string filePath) { //获取文件的名称 FileInfo fi = new FileInfo(filePath); return fi.Name; } #endregion #region 文件创建操作 /// <summary> /// 创建文件 /// </summary> /// <param name="dir">带后缀的文件名</param> /// <param name="pagestr">文件内容</param> public static void CreateFile(string dir, string pagestr) { dir = dir.Replace("/", "\\"); if (dir.IndexOf("\\") > -1) CreateDir(dir.Substring(0, dir.LastIndexOf("\\"))); StreamWriter sw = new StreamWriter(dir, false, System.Text.Encoding.GetEncoding("GB2312")); sw.Write(pagestr); sw.Close(); } /// <summary> /// 创建一个文件。 /// </summary> /// <param name="filePath">文件的绝对路径</param> public static void CreateFile(string filePath) { try { //如果文件不存在则创建该文件 if (!IsExistFile(filePath)) { //创建一个FileInfo对象 FileInfo file = new FileInfo(filePath); //创建文件 FileStream fs = file.Create(); //关闭文件流 fs.Close(); } } catch (Exception ex) { throw ex; } } /// <summary> /// 创建一个文件,并将字节流写入文件。 /// </summary> /// <param name="filePath">文件的绝对路径</param> /// <param name="buffer">二进制流数据</param> public static void CreateFile(string filePath, byte[] buffer) { try { //如果文件不存在则创建该文件 if (!IsExistFile(filePath)) { //创建一个FileInfo对象 FileInfo file = new FileInfo(filePath); //创建文件 FileStream fs = file.Create(); //写入二进制流 fs.Write(buffer, 0, buffer.Length); //关闭文件流 fs.Close(); } } catch (Exception ex) { throw ex; } } #endregion #region 文件写入操作 /// <summary> /// 向文本文件中写入内容 /// </summary> /// <param name="filePath">文件的绝对路径</param> /// <param name="text">写入的内容</param> /// <param name="encoding">编码</param> public static void WriteText(string filePath, string text, Encoding encoding) { //向文件写入内容 File.WriteAllText(filePath, text, encoding); } /// <summary> /// 向文本文件的尾部追加内容 /// </summary> /// <param name="filePath">文件的绝对路径</param> /// <param name="content">写入的内容</param> public static void AppendText(string filePath, string content, Encoding encoding) { File.AppendAllText(filePath, content, encoding); } #endregion #region 文件删除、移动、复制操作 /// <summary> /// 将源文件的内容复制到目标文件中 /// </summary> /// <param name="sourceFilePath">源文件的绝对路径</param> /// <param name="destFilePath">目标文件的绝对路径</param> public static void Copy(string sourceFilePath, string destFilePath) { File.Copy(sourceFilePath, destFilePath, true); } /// <summary> /// 将文件移动到指定目录 /// </summary> /// <param name="sourceFilePath">需要移动的源文件的绝对路径</param> /// <param name="descDirectoryPath">移动到的目录的绝对路径</param> public static void Move(string sourceFilePath, string descDirectoryPath) { //获取源文件的名称 string sourceFileName = GetFileName(sourceFilePath); if (IsExistDirectory(descDirectoryPath)) { //如果目标中存在同名文件,则删除 if (IsExistFile(descDirectoryPath + "\\" + sourceFileName)) { DeleteFile(descDirectoryPath + "\\" + sourceFileName); } //将文件移动到指定目录 File.Move(sourceFilePath, descDirectoryPath + "\\" + sourceFileName); } } /// <summary> /// 删除文件 /// </summary> /// <param name="file">要删除的文件路径和名称</param> public static void DeleteFile(string file) { if (File.Exists(file)) File.Delete(file); } /// <summary> /// 移动文件(剪贴--粘贴),移动后重命名,已经存在就会出错 /// </summary> /// <param name="dir1">要移动的文件的路径及全名(包括后缀)</param> /// <param name="dir2">文件移动到新的位置,并指定新的文件名</param> public static void MoveFile(string dir1, string dir2) { dir1 = dir1.Replace("/", "\\"); dir2 = dir2.Replace("/", "\\"); if (File.Exists(dir1)) File.Move(dir1, dir2); } /// <summary> /// 复制文件 /// </summary> /// <param name="dir1">要复制的文件的路径已经全名(包括后缀)</param> /// <param name="dir2">目标位置,并指定新的文件名</param> public static void CopyFile(string dir1, string dir2) { dir1 = dir1.Replace("/", "\\"); dir2 = dir2.Replace("/", "\\"); if (File.Exists(dir1)) { File.Copy(dir1, dir2, true); } } /// <summary> /// 备份文件 /// </summary> /// <param name="sourceFileName">源文件名</param> /// <param name="destFileName">目标文件名</param> /// <param name="overwrite">当目标文件存在时是否覆盖</param> /// <returns>操作是否成功</returns> public static bool CopyFile(string sourceFileName, string destFileName, bool overwrite) { if (!File.Exists(sourceFileName)) { throw new FileNotFoundException(sourceFileName + "文件不存在!"); } if (!overwrite && File.Exists(destFileName)) { return false; } try { File.Copy(sourceFileName, destFileName, true); return true; } catch (Exception e) { throw e; } } /// <summary> /// 清空文件内容 /// </summary> /// <param name="filePath">文件的绝对路径</param> public static void ClearFile(string filePath) { //删除文件 File.Delete(filePath); //重新创建该文件 CreateFile(filePath); } #endregion #region 文件读取操作 /// <summary> /// 根据时间得到文件名HHmmssff /// </summary> /// <returns></returns> public static string GetDateFile() { return DateTime.Now.ToString("HHmmssff"); } /// <summary> /// 获取文本文件的行数 /// </summary> /// <param name="filePath">文件的绝对路径</param> public static int GetLineCount(string filePath) { //将文本文件的各行读到一个字符串数组中 string[] rows = File.ReadAllLines(filePath); //返回行数 return rows.Length; } /// <summary> /// 获取一个文件的长度,单位为Byte /// </summary> /// <param name="filePath">文件的绝对路径</param> public static string GetFileSize(string filePath, bool isNum) { if (isNum) { //创建一个文件对象 FileInfo fi = new FileInfo(filePath); //获取文件的大小 return fi.Length.ToString(); } else { if (File.Exists(filePath) == true) { FileInfo fileinfo = new FileInfo(filePath); long fl = fileinfo.Length; if (fl > 1024 * 1024 * 1024) { return Convert.ToString(Math.Round((fl + 0.00) / (1024 * 1024 * 1024), 2)) + " GB"; } else if (fl > 1024 * 1024) { return Convert.ToString(Math.Round((fl + 0.00) / (1024 * 1024), 2)) + " MB"; } else { return Convert.ToString(Math.Round((fl + 0.00) / 1024, 2)) + " KB"; } } else { return null; } } } /// <summary> /// 从文件的绝对路径中获取文件名( 不包含扩展名 ) /// </summary> /// <param name="filePath">文件的绝对路径</param> public static string GetFileNameNoExtension(string filePath) { //获取文件的名称 FileInfo fi = new FileInfo(filePath); return fi.Name.Split('.')[0]; } /// <summary> /// 从文件的绝对路径中获取扩展名 /// </summary> /// <param name="filePath">文件的绝对路径</param> public static string GetExtension(string filePath) { //获取文件的名称 FileInfo fi = new FileInfo(filePath); return fi.Extension; } #endregion #endregion #region 文件夹操作 #region 删除、复制文件夹 /// <summary> /// 复制文件夹(递归) /// </summary> /// <param name="varFromDirectory">源文件夹路径</param> /// <param name="varToDirectory">目标文件夹路径</param> public static void CopyFolder(string varFromDirectory, string varToDirectory) { Directory.CreateDirectory(varToDirectory); if (!Directory.Exists(varFromDirectory)) return; string[] directories = Directory.GetDirectories(varFromDirectory); if (directories.Length > 0) { foreach (string d in directories) { string tD = varToDirectory + d.Substring(d.LastIndexOf("\\")); CopyFolder(d, tD); } } string[] files = Directory.GetFiles(varFromDirectory); if (files.Length > 0) { foreach (string s in files) { string tF = varToDirectory + "/" + FileHelper.GetFileName(s); File.Copy(s, tF, true); } } } /// <summary> /// 删除指定文件夹对应其他文件夹里的文件 /// </summary> /// <param name="varFromDirectory">指定文件夹路径</param> /// <param name="varToDirectory">对应其他文件夹路径</param> public static void DeleteFolderFiles(string varFromDirectory, string varToDirectory) { Directory.CreateDirectory(varToDirectory); if (!Directory.Exists(varFromDirectory)) return; string[] directories = Directory.GetDirectories(varFromDirectory); if (directories.Length > 0) { foreach (string d in directories) { string tD = varToDirectory + d.Substring(d.LastIndexOf("\\")); DeleteFolderFiles(d, tD); } } string[] files = Directory.GetFiles(varFromDirectory); if (files.Length > 0) { foreach (string s in files) { string tF = varToDirectory + "/" + FileHelper.GetFileName(s); File.Delete(tF); } } } #endregion #endregion #region 文件目录操作 #region 文件目录检查操作 /// <summary> /// 检测指定目录是否为空 /// </summary> /// <param name="directoryPath">指定目录的绝对路径</param> public static bool IsEmptyDirectory(string directoryPath) { try { //判断是否存在文件 string[] fileNames = GetFileNames(directoryPath); if (fileNames.Length > 0) { return false; } //判断是否存在文件夹 string[] directoryNames = GetDirectories(directoryPath); if (directoryNames.Length > 0) { return false; } return true; } catch { return true; } } /// <summary> /// 检测指定目录是否存在 /// </summary> /// <param name="directoryPath">目录的绝对路径</param> /// <returns></returns> public static bool IsExistDirectory(string directoryPath) { return Directory.Exists(directoryPath); } /// <summary> /// 检测指定目录中是否存在指定的文件,若要搜索子目录请使用重载方法. /// </summary> /// <param name="directoryPath">指定目录的绝对路径</param> /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。 /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param> public static bool Contains(string directoryPath, string searchPattern) { try { //获取指定的文件列表 string[] fileNames = GetFileNames(directoryPath, searchPattern, false); //判断指定文件是否存在 if (fileNames.Length == 0) { return false; } else { return true; } } catch (Exception ex) { throw new Exception(ex.Message); //LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message); } } /// <summary> /// 检测指定目录中是否存在指定的文件 /// </summary> /// <param name="directoryPath">指定目录的绝对路径</param> /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。 /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param> /// <param name="isSearchChild">是否搜索子目录</param> public static bool Contains(string directoryPath, string searchPattern, bool isSearchChild) { try { //获取指定的文件列表 string[] fileNames = GetFileNames(directoryPath, searchPattern, true); //判断指定文件是否存在 if (fileNames.Length == 0) { return false; } else { return true; } } catch (Exception ex) { throw new Exception(ex.Message); //LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message); } } #endregion #region 文件目录创建操作 /// <summary> /// 创建目录 /// </summary> /// <param name="dir">要创建的目录路径包括目录名</param> public static void CreateDir(string dir) { if (dir.Length == 0) return; if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); } /// <summary> /// 创建一个目录 /// </summary> /// <param name="directoryPath">目录的绝对路径</param> public static void CreateDirectory(string directoryPath) { //如果目录不存在则创建该目录 if (!IsExistDirectory(directoryPath)) { Directory.CreateDirectory(directoryPath); } } #endregion #region 文件目录删除、移动、复制操作 /// <summary> /// 删除目录 /// </summary> /// <param name="dir">要删除的目录路径和名称</param> public static void DeleteDir(string dir) { if (dir.Length == 0) return; if (Directory.Exists(dir)) Directory.Delete(dir); } /// <summary> /// 清空指定目录下所有文件及子目录,但该目录依然保存. /// </summary> /// <param name="directoryPath">指定目录的绝对路径</param> public static void ClearDirectory(string directoryPath) { if (IsExistDirectory(directoryPath)) { //删除目录中所有的文件 string[] fileNames = GetFileNames(directoryPath); for (int i = 0; i < fileNames.Length; i++) { DeleteFile(fileNames[i]); } //删除目录中所有的子目录 string[] directoryNames = GetDirectories(directoryPath); for (int i = 0; i < directoryNames.Length; i++) { DeleteDirectory(directoryNames[i]); } } } /// <summary> /// 删除指定目录及其所有子目录 /// </summary> /// <param name="directoryPath">指定目录的绝对路径</param> public static void DeleteDirectory(string directoryPath) { if (IsExistDirectory(directoryPath)) { Directory.Delete(directoryPath, true); } } #endregion #region 文件目录读取操作 /// <summary> /// 获取指定目录中所有子目录列表,若要搜索嵌套的子目录列表,请使用重载方法. /// </summary> /// <param name="directoryPath">指定目录的绝对路径</param> public static string[] GetDirectories(string directoryPath) { try { return Directory.GetDirectories(directoryPath); } catch (IOException ex) { throw ex; } } /// <summary> /// 获取指定目录中所有文件列表 /// </summary> /// <param name="directoryPath">指定目录的绝对路径</param> public static string[] GetFileNames(string directoryPath) { //如果目录不存在,则抛出异常 if (!IsExistDirectory(directoryPath)) { throw new FileNotFoundException(); } //获取文件列表 return Directory.GetFiles(directoryPath); } /// <summary> /// 获取指定目录及子目录中所有文件列表 /// </summary> /// <param name="directoryPath">指定目录的绝对路径</param> /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。 /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param> /// <param name="isSearchChild">是否搜索子目录</param> public static string[] GetFileNames(string directoryPath, string searchPattern, bool isSearchChild) { //如果目录不存在,则抛出异常 if (!IsExistDirectory(directoryPath)) { throw new FileNotFoundException(); } try { if (isSearchChild) { return Directory.GetFiles(directoryPath, searchPattern, SearchOption.AllDirectories); } else { return Directory.GetFiles(directoryPath, searchPattern, SearchOption.TopDirectoryOnly); } } catch (IOException ex) { throw ex; } } /// <summary> /// 获得指定目录下的文件列表 /// </summary> /// <param name="path">路径</param> /// <returns></returns> public static string[] GetDirectoryFileList(string path, string searchPattern) { if (!Directory.Exists(path)) return new string[0]; DirectoryInfo dirInfo = new DirectoryInfo(path); FileInfo[] fileInfos = dirInfo.GetFiles(searchPattern); string[] result = new string[fileInfos.Length]; for (int i = 0; i < fileInfos.Length; i++) { result[i] = fileInfos[i].Name; } return result; } /// <summary> /// 获取指定目录的所有文件列表 /// </summary> /// <param name="path"></param> /// <returns></returns> public static string[] GetDirectoryFileList(string path) { return GetDirectoryFileList(path, "*.*"); } /// <summary> /// 根据时间得到目录名yyyyMMdd /// </summary> /// <returns></returns> public static string GetDateDir() { return DateTime.Now.ToString("yyyyMMdd"); } #endregion #endregion #region 文件流操作 /// <summary> /// 将流读取到缓冲区中 /// </summary> /// <param name="stream">原始流</param> public static byte[] StreamToBytes(Stream stream) { try { //创建缓冲区 byte[] buffer = new byte[stream.Length]; //读取流 stream.Read(buffer, 0, Convert.ToInt32(stream.Length)); //返回流 return buffer; } catch (IOException ex) { throw ex; } finally { //关闭流 stream.Close(); } } /// <summary> /// 将 byte[] 转成 Stream /// </summary> public static Stream BytesToStream(byte[] bytes) { Stream stream = new MemoryStream(bytes); return stream; } /// <summary> /// 将 Stream 写入文件 /// </summary> public static void StreamToFile(Stream stream, string fileName) { // 把 Stream 转换成 byte[] byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); // 设置当前流的位置为流的开始 stream.Seek(0, SeekOrigin.Begin); // 把 byte[] 写入文件 FileStream fs = new FileStream(fileName, FileMode.Create); BinaryWriter bw = new BinaryWriter(fs); bw.Write(bytes); bw.Close(); fs.Close(); } /// <summary> /// 从文件读取 Stream /// </summary> public static Stream FileToStream(string fileName) { // 打开文件 FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); // 读取文件的 byte[] byte[] bytes = new byte[fileStream.Length]; fileStream.Read(bytes, 0, bytes.Length); fileStream.Close(); // 把 byte[] 转换成 Stream Stream stream = new MemoryStream(bytes); return stream; } /// <summary> /// 文件转字节流 /// </summary> /// <param name="path">文件路径</param> /// <returns></returns> public static byte[] FileToBytes(string path) { FileStream fs = File.OpenRead(path); MemoryStream ms = new MemoryStream(); int bdata; while ((bdata = fs.ReadByte()) != -1) { ms.WriteByte(((byte)bdata)); } byte[] data = (byte[])ms.ToArray(); fs.Close(); ms.Close(); return data; } /// <summary> /// 把流生成文件 /// </summary> /// <param name="buffer">文件流</param> /// <param name="fileName">要生成的文件名【路】</param> public static bool UpLoadFile(byte[] buffer, string filePath) { try { //如果文件不存在则创建该文件 if (!IsExistFile(filePath)) { //创建文件 using (FileStream fs = File.Create(filePath)) { //写入二进制流 fs.Write(buffer, 0, buffer.Length); } return true; } } catch { return false; } return false; } /// <summary> /// 图片转为base64编码 /// </summary> /// <param name="filePath">路径</param> /// <returns></returns> public static string ImgToBase64String(string filePath) { try { Bitmap bmp = new Bitmap(filePath); MemoryStream ms = new MemoryStream(); bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] arr = new byte[ms.Length]; ms.Position = 0; ms.Read(arr, 0, (int)ms.Length); ms.Close(); return Convert.ToBase64String(arr); } catch (Exception e) { //Logger.WriteLog("图片转为base64编码出现异常\r\n" + e.Message + "\r\n"); } return ""; } /// <summary> /// 图片转为base64编码 /// </summary> /// <param name="bmp">图片流</param> /// <returns></returns> public static string ImgToBase64String(Bitmap bmp) { try { MemoryStream ms = new MemoryStream(); bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] arr = new byte[ms.Length]; ms.Position = 0; ms.Read(arr, 0, (int)ms.Length); ms.Close(); return Convert.ToBase64String(arr); } catch (Exception e) { //Logger.WriteLog("图片转为base64编码出现异常\r\n" + e.Message + "\r\n"); } return ""; } /// <summary> /// base64编码的文本转为图片 /// </summary> /// <param name="photo">base64编码</param> /// <param name="filePath">保存绝对路径</param> /// <returns></returns> public static bool Base64ToImage(string photo, string filePath) { try { string dirpath = filePath;//文件保存路径 if (!Directory.Exists(dirpath)) { Directory.CreateDirectory(dirpath); } if (File.Exists(filePath)) { File.Delete(filePath); } byte[] arr = Convert.FromBase64String(photo); MemoryStream ms = new MemoryStream(arr); ms.Write(arr, 0, arr.Length); Bitmap bmp = new Bitmap(ms); bmp.Save(filePath, ImageFormat.Png); bmp.Dispose(); return true; } catch (Exception e) { //Logger.WriteLog("base64编码的文本转为图片出现异常\r\n" + e.Message + "\r\n base64编码" + photo + "\r\n"); return false; } } /// <summary> /// 根据图片路径返回图片的字节流byte[] /// </summary> /// <param name="imagePath">图片路径</param> /// <returns>返回的字节流</returns> public static byte[] ImageToByte(string imagePath) { try { FileStream files = new FileStream(imagePath, FileMode.Open); byte[] imgByte = new byte[files.Length]; files.Read(imgByte, 0, imgByte.Length); files.Close(); return imgByte; } catch (Exception ee) { return null; } } /// <summary> /// 图片转换成字节流 /// </summary> /// <param name="bmp">要转换的Image对象</param> /// <returns>转换后返回的字节流</returns> public static byte[] ImgToByte(Bitmap bmp) { MemoryStream ms = new MemoryStream(); byte[] imagedata = null; bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); imagedata = ms.GetBuffer(); bmp.Dispose(); return imagedata; } /// <summary> /// 字节流转换成图片 /// </summary> /// <param name="byt">要转换的字节流</param> /// <returns>转换得到的Image对象</returns> public static Image ByteToImg(byte[] byt) { try { MemoryStream ms = new MemoryStream(byt); Image img = Image.FromStream(ms); return img; } catch (Exception ee) { return null; } } /// <summary> /// 计算文件大小函数(保留两位小数),Size为字节大小 /// </summary> /// <param name="Size">初始文件大小</param> /// <returns></returns> public static string CountSize(long Size) { string m_strSize = ""; long FactSize = 0; FactSize = Size; if (FactSize < 1024.00) m_strSize = FactSize.ToString("F2") + " 字节"; else if (FactSize >= 1024.00 && FactSize < 1048576) m_strSize = (FactSize / 1024.00).ToString("F2") + " KB"; else if (FactSize >= 1048576 && FactSize < 1073741824) m_strSize = (FactSize / 1024.00 / 1024.00).ToString("F2") + " MB"; else if (FactSize >= 1073741824) m_strSize = (FactSize / 1024.00 / 1024.00 / 1024.00).ToString("F2") + " GB"; return m_strSize; } /// <summary> /// 获取文件夹大小 /// </summary> /// <param name="path"></param> /// <returns></returns> public static string GetDictSize(string path) { if (!Directory.Exists(path)) return "0"; string[] fs = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories); //获取该文件夹中所有的文件名 long ll = 0; foreach (string f in fs) { dynamic fa = File.GetAttributes(f); FileInfo fi = new FileInfo(f); ll += fi.Length; } return CountSize(ll); } /// <summary> /// 将文件转换为文件字符流 /// </summary> /// <param name="FilePath"></param> /// <returns></returns> public static string FileToBinary(string FilePath) { FileStream input = new FileStream(FilePath, FileMode.Open, FileAccess.Read); int count = Convert.ToInt32(input.Length); byte[] buffer = new byte[count]; BinaryReader reader = new BinaryReader(input); for (int i = 0; i < count; i++) { reader.Read(buffer, 0, count); } input.Close(); return Convert.ToBase64String(buffer); } /// <summary> /// 将字符流转换为文件 /// </summary> /// <param name="path"></param> /// <param name="Binary"></param> public static void BinaryToFile(string path, string Binary) { FileStream output = new FileStream(path, FileMode.Create, FileAccess.Write); BinaryWriter writer = new BinaryWriter(output); writer.Write(Convert.FromBase64String(Binary)); writer.Close(); output.Close(); } #endregion }
显示效果:
可以使用不同的文件类库进行文件操作,但大体都差不多。
以上类库内容来源互联网,站长稍作整理
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。