C# 文件操作
文件操作
文件名处理
//替换掉非法字符 fileName = fileName.Replace(":", "_").Replace(" ", "_").Replace("\\", "_").Replace("/", "_");
获取目录下所有文件的文件名
String path = @"X:\xxx\xxx"; //第一种方法 var files = Directory.GetFiles(path, "*.txt"); foreach (var file in files) Console.WriteLine(file); //第二种方法 DirectoryInfo folder = new DirectoryInfo(path); foreach (FileInfo file in folder.GetFiles("*.txt")) { Console.WriteLine(file.FullName); }
C#判断文件和目录是否存在,不存在则创建
文件: if (File.Exists(Server.MapPath("~/upimg/Data.html"))){ File.Create(MapPath("~/upimg/Data.html"));//创建该文件 } 文件夹: if (!Directory.Exists(Server.MapPath("~/upimg/hufu"))){ Directory.CreateDirectory(Server.MapPath("~/upimg/hufu")); }
删除文件
/// <summary> /// 删除单个文件 /// </summary> /// <param name="_filepath">文件相对路径</param> public static bool DeleteFile(string _filepath) { if (string.IsNullOrEmpty(_filepath)) { return false; } string fullpath = GetMapPath(_filepath); if (File.Exists(fullpath)) { File.Delete(fullpath); return true; } return false; } /// <summary> /// 删除上传的文件(及缩略图) /// </summary> /// <param name="_filepath"></param> public static void DeleteUpFile(string _filepath) { if (string.IsNullOrEmpty(_filepath)) { return; } string thumbnailpath = _filepath.Substring(0, _filepath.LastIndexOf("/")) + "mall_" + _filepath.Substring(_filepath.LastIndexOf("/") + 1); string fullTPATH = GetMapPath(_filepath); //宿略图 string fullpath = GetMapPath(_filepath); //原图 if (File.Exists(fullpath)) { File.Delete(fullpath); } if (File.Exists(fullTPATH)) { File.Delete(fullTPATH); } }
返回文件大小 KB
/// <summary> /// 返回文件大小 KB /// </summary> /// <param name="_filepath">文件相对路径</param> /// <returns>int</returns> public static int GetFileSize(string _filepath) { if (string.IsNullOrEmpty(_filepath)) { return 0; } string fullpath = GetMapPath(_filepath); if (File.Exists(fullpath)) { FileInfo fileInfo = new FileInfo(fullpath); return ((int)fileInfo.Length) / 1024; } return 0; }
返回文件扩展名,不含“.”
/// <summary> /// 返回文件扩展名,不含“.” /// </summary> /// <param name="_filepath">文件全名称</param> /// <returns>string</returns> public static string GetFileExt(string _filepath) { if (string.IsNullOrEmpty(_filepath)) { return ""; } if (_filepath.LastIndexOf(".") > 0) { return _filepath.Substring(_filepath.LastIndexOf(".") + 1); //文件扩展名,不含“.” } return ""; }
文件下载
TransmitFile 方式
/* 微软为 Response 对象提供了一个新的方法 TransmitFile 来解决使用 Response.BinaryWrite 下载超过 400MB 的文件时, 导致 Aspnet_wp.exe 进程回收而无法成功下载的问题。 代码如下:*/ Response.ContentType = "application/x-zip-compressed"; string FileName = "test.doc"; //使用 UTF-8 对文件名进行编码 Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + "\""); Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName); string filename = Server.MapPath("../ReportTemplate/test.doc"); Response.TransmitFile(filename);
WriteFile 方式
/* using System.IO; */ string fileName = "test.doc";//客户端保存的文件名 string filePath = Server.MapPath("../ReportTemplate/test.doc");//路径 FileInfo fileInfo = new FileInfo(filePath); Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); Response.AddHeader("Content-Disposition", "attachment;filename=\"" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + "\""); Response.AddHeader("Content-Length", fileInfo.Length.ToString()); Response.AddHeader("Content-Transfer-Encoding", "binary"); Response.ContentType = "application/octet-stream"; Response.WriteFile(fileInfo.FullName); Response.Flush(); Response.End();
WriteFile 分块下载方式
string fileName = "test.doc";//客户端保存的文件名 string filePath = Server.MapPath("../ReportTemplate/test.doc");//路径 System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath); if (fileInfo.Exists == true) { const long ChunkSize = 102400; //100K 每次读取文件,只读取 100K,这样可以缓解服务器的压力 byte[] buffer = new byte[ChunkSize]; Response.Clear(); System.IO.FileStream iStream = System.IO.File.OpenRead(filePath); long dataLengthToRead = iStream.Length; //获取下载的文件总大小 Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); while (dataLengthToRead > 0 && Response.IsClientConnected) { int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize)); //读取的大小 Response.OutputStream.Write(buffer, 0, lengthRead); Response.Flush(); dataLengthToRead = dataLengthToRead - lengthRead; } Response.Close(); }
流方式下载
string fileName = "test.doc";//客户端保存的文件名 string filePath = Server.MapPath("../ReportTemplate/test.doc");//路径 //以字符流的形式下载文件 FileStream fs = new FileStream(filePath, FileMode.Open); byte[] bytes = new byte[(int)fs.Length]; fs.Read(bytes, 0, bytes.Length); fs.Close(); Response.ContentType = "application/octet-stream"; //通知浏览器下载文件而不是打开 Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); Response.BinaryWrite(bytes); Response.Flush(); Response.End();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
上一篇: C# DataTable 序列化
下一篇: 彻底找到 Tomcat 启动速度慢的元凶
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论