Asp.net(c#)中常用文件操作类封装
包括:移动 复制 删除 上传 下载等
using System; using System.Configuration; using System.Data; using System.IO; using System.Text; using System.Threading; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; namespace MSCL { /// <summary> /// 文件或文件夹操作类 /// </summary> public class FileHelper { #region 构造函数 private bool _alreadyDispose = false; /// <summary> /// 释放资源返回bool /// </summary> /// <param name="isDisposing"></param> protected virtual void Dispose(bool isDisposing) { if (_alreadyDispose) return; //if (isDisposing) //{ // if (xml != null) // { // xml = null; // } //} _alreadyDispose = true; } #endregion #region IDisposable 成员 /// <summary> /// 释放资源 /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion #region 取得文件后缀名 /**************************************** * 函数名称:GetPostfixStr * 功能说明:取得文件后缀名 * 参 数:filename:文件名称 * 调用示列: * string filename = "aaa.aspx"; * string s = EC.FileObj.GetPostfixStr(filename); *****************************************/ /// <summary> /// 取后缀名 /// </summary> /// <param name="filename">文件名</param> /// <returns>.gif|.html格式</returns> public static string GetPostfixStr(string filename) { int start = filename.LastIndexOf("."); int length = filename.Length; string postfix = filename.Substring(start, length - start); return postfix; } #endregion #region 写文件 /**************************************** * 函数名称:WriteFile * 功能说明:当文件不存时,则创建文件,并追加文件 * 参 数:Path:文件路径,Strings:文本内容 * 调用示列: * string Path = Server.MapPath("Default2.aspx"); * string Strings = "这是我写的内容啊"; * EC.FileObj.WriteFile(Path,Strings); *****************************************/ /// <summary> /// 写文件 /// </summary> /// <param name="Path">文件路径</param> /// <param name="Strings">文件内容</param> public static void WriteFile(string Path, string Strings) { if (!System.IO.File.Exists(Path)) { //Directory.CreateDirectory(Path); System.IO.FileStream f = System.IO.File.Create(Path); f.Close(); f.Dispose(); } System.IO.StreamWriter f2 = new System.IO.StreamWriter(Path, true, System.Text.Encoding.UTF8); f2.WriteLine(Strings); f2.Close(); f2.Dispose(); } #endregion #region 读文件 /**************************************** * 函数名称:ReadFile * 功能说明:读取文本内容 * 参 数:Path:文件路径 * 调用示列: * string Path = Server.MapPath("Default2.aspx"); * string s = EC.FileObj.ReadFile(Path); *****************************************/ /// <summary> /// 读文件 /// </summary> /// <param name="Path">文件路径</param> /// <returns></returns> public static string ReadFile(string Path) { string s = ""; if (!System.IO.File.Exists(Path)) s = "不存在相应的目录"; else { StreamReader f2 = new StreamReader(Path, System.Text.Encoding.GetEncoding("gb2312")); s = f2.ReadToEnd(); f2.Close(); f2.Dispose(); } return s; } #endregion #region 追加文件 /**************************************** * 函数名称:FileAdd * 功能说明:追加文件内容 * 参 数:Path:文件路径,strings:内容 * 调用示列: * string Path = Server.MapPath("Default2.aspx"); * string Strings = "新追加内容"; * EC.FileObj.FileAdd(Path, Strings); *****************************************/ /// <summary> /// 追加文件 /// </summary> /// <param name="Path">文件路径</param> /// <param name="strings">内容</param> public static void FileAdd(string Path, string strings) { StreamWriter sw = File.AppendText(Path); sw.Write(strings); sw.Flush(); sw.Close(); sw.Dispose(); } #endregion #region 拷贝文件 /**************************************** * 函数名称:FileCoppy * 功能说明:拷贝文件 * 参 数:OrignFile:原始文件,NewFile:新文件路径 * 调用示列: * string OrignFile = Server.MapPath("Default2.aspx"); * string NewFile = Server.MapPath("Default3.aspx"); * EC.FileObj.FileCoppy(OrignFile, NewFile); *****************************************/ /// <summary> /// 拷贝文件 /// </summary> /// <param name="OrignFile">原始文件</param> /// <param name="NewFile">新文件路径</param> public static void FileCoppy(string OrignFile, string NewFile) { File.Copy(OrignFile, NewFile, true); } #endregion #region 删除文件 /**************************************** * 函数名称:FileDel * 功能说明:删除文件 * 参 数:Path:文件路径 * 调用示列: * string Path = Server.MapPath("Default3.aspx"); * EC.FileObj.FileDel(Path); *****************************************/ /// <summary> /// 删除文件 /// </summary> /// <param name="Path">路径</param> public static void FileDel(string Path) { File.Delete(Path); } #endregion #region 移动文件 /**************************************** * 函数名称:FileMove * 功能说明:移动文件 * 参 数:OrignFile:原始路径,NewFile:新文件路径 * 调用示列: * string OrignFile = Server.MapPath("../说明.txt"); * string NewFile = Server.MapPath("../../说明.txt"); * EC.FileObj.FileMove(OrignFile, NewFile); *****************************************/ /// <summary> /// 移动文件 /// </summary> /// <param name="OrignFile">原始路径</param> /// <param name="NewFile">新路径</param> public static void FileMove(string OrignFile, string NewFile) { File.Move(OrignFile, NewFile); } #endregion #region 在当前目录下创建目录 /**************************************** * 函数名称:FolderCreate * 功能说明:在当前目录下创建目录 * 参 数:OrignFolder:当前目录,NewFloder:新目录 * 调用示列: * string OrignFolder = Server.MapPath("test/"); * string NewFloder = "new"; * EC.FileObj.FolderCreate(OrignFolder, NewFloder); *****************************************/ /// <summary> /// 在当前目录下创建目录 /// </summary> /// <param name="OrignFolder">当前目录</param> /// <param name="NewFloder">新目录</param> public static void FolderCreate(string OrignFolder, string NewFloder) { Directory.SetCurrentDirectory(OrignFolder); Directory.CreateDirectory(NewFloder); } /// <summary> /// 创建文件夹 /// </summary> /// <param name="Path"></param> public static void FolderCreate(string Path) { // 判断目标目录是否存在如果不存在则新建之 if (!Directory.Exists(Path)) Directory.CreateDirectory(Path); } #endregion #region 创建目录 /// <summary> /// 创建目录 /// </summary> /// <param name="Path"></param> public static void FileCreate(string Path) { FileInfo CreateFile = new FileInfo(Path); //创建文件 if (!CreateFile.Exists) { FileStream FS = CreateFile.Create(); FS.Close(); } } #endregion #region 递归删除文件夹目录及文件 /**************************************** * 函数名称:DeleteFolder * 功能说明:递归删除文件夹目录及文件 * 参 数:dir:文件夹路径 * 调用示列: * string dir = Server.MapPath("test/"); * EC.FileObj.DeleteFolder(dir); *****************************************/ /// <summary> /// 递归删除文件夹目录及文件 /// </summary> /// <param name="dir"></param> /// <returns></returns> public static void DeleteFolder(string 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); //删除已空文件夹 } } #endregion #region 将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。 /**************************************** * 函数名称:CopyDir * 功能说明:将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。 * 参 数:srcPath:原始路径,aimPath:目标文件夹 * 调用示列: * string srcPath = Server.MapPath("test/"); * string aimPath = Server.MapPath("test1/"); * EC.FileObj.CopyDir(srcPath,aimPath); *****************************************/ /// <summary> /// 指定文件夹下面的所有内容copy到目标文件夹下面 /// </summary> /// <param name="srcPath">原始路径</param> /// <param name="aimPath">目标文件夹</param> public static void CopyDir(string srcPath, string aimPath) { try { // 检查目标目录是否以目录分割字符结束如果不是则添加之 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(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()); } } #endregion #region 获取指定文件夹下所有子目录及文件(树形) /**************************************** * 函数名称:GetFoldAll(string Path) * 功能说明:获取指定文件夹下所有子目录及文件(树形) * 参 数:Path:详细路径 * 调用示列: * string strDirlist = Server.MapPath("templates"); * this.Literal1.Text = EC.FileObj.GetFoldAll(strDirlist); *****************************************/ /// <summary> /// 获取指定文件夹下所有子目录及文件 /// </summary> /// <param name="Path">详细路径</param> public static string GetFoldAll(string Path) { string str = ""; DirectoryInfo thisOne = new DirectoryInfo(Path); str = ListTreeShow(thisOne, 0, str); return str; } /// <summary> /// 获取指定文件夹下所有子目录及文件函数 /// </summary> /// <param name="theDir">指定目录</param> /// <param name="nLevel">默认起始值,调用时,一般为0</param> /// <param name="Rn">用于迭加的传入值,一般为空</param> /// <returns></returns> public static string ListTreeShow(DirectoryInfo theDir, int nLevel, string Rn)//递归目录 文件 { DirectoryInfo[] subDirectories = theDir.GetDirectories();//获得目录 foreach (DirectoryInfo dirinfo in subDirectories) { if (nLevel == 0) { Rn += "├"; } else { string _s = ""; for (int i = 1; i <= nLevel; i++) { _s += "│ "; } Rn += _s + "├"; } Rn += "<b>" + dirinfo.Name.ToString() + "</b><br />"; FileInfo[] fileInfo = dirinfo.GetFiles(); //目录下的文件 foreach (FileInfo fInfo in fileInfo) { if (nLevel == 0) { Rn += "│ ├"; } else { string _f = ""; for (int i = 1; i <= nLevel; i++) { _f += "│ "; } Rn += _f + "│ ├"; } Rn += fInfo.Name.ToString() + " <br />"; } Rn = ListTreeShow(dirinfo, nLevel + 1, Rn); } return Rn; } /**************************************** * 函数名称:GetFoldAll(string Path) * 功能说明:获取指定文件夹下所有子目录及文件(下拉框形) * 参 数:Path:详细路径 * 调用示列: * string strDirlist = Server.MapPath("templates"); * this.Literal2.Text = EC.FileObj.GetFoldAll(strDirlist,"tpl",""); *****************************************/ /// <summary> /// 获取指定文件夹下所有子目录及文件(下拉框形) /// </summary> /// <param name="Path">详细路径</param> ///<param name="DropName">下拉列表名称</param> ///<param name="tplPath">默认选择模板名称</param> public static string GetFoldAll(string Path, string DropName, string tplPath) { string strDrop = "<select name=\"" + DropName + "\" id=\"" + DropName + "\"><option value=\"\">--请选择详细模板--</option>"; string str = ""; DirectoryInfo thisOne = new DirectoryInfo(Path); str = ListTreeShow(thisOne, 0, str, tplPath); return strDrop + str + "</select>"; } /// <summary> /// 获取指定文件夹下所有子目录及文件函数 /// </summary> /// <param name="theDir">指定目录</param> /// <param name="nLevel">默认起始值,调用时,一般为0</param> /// <param name="Rn">用于迭加的传入值,一般为空</param> /// <param name="tplPath">默认选择模板名称</param> /// <returns></returns> public static string ListTreeShow(DirectoryInfo theDir, int nLevel, string Rn, string tplPath)//递归目录 文件 { DirectoryInfo[] subDirectories = theDir.GetDirectories();//获得目录 foreach (DirectoryInfo dirinfo in subDirectories) { Rn += "<option value=\"" + dirinfo.Name.ToString() + "\""; if (tplPath.ToLower() == dirinfo.Name.ToString().ToLower()) { Rn += " selected "; } Rn += ">"; if (nLevel == 0) { Rn += "┣"; } else { string _s = ""; for (int i = 1; i <= nLevel; i++) { _s += "│ "; } Rn += _s + "┣"; } Rn += "" + dirinfo.Name.ToString() + "</option>"; FileInfo[] fileInfo = dirinfo.GetFiles(); //目录下的文件 foreach (FileInfo fInfo in fileInfo) { Rn += "<option value=\"" + dirinfo.Name.ToString() + "/" + fInfo.Name.ToString() + "\""; if (tplPath.ToLower() == fInfo.Name.ToString().ToLower()) { Rn += " selected "; } Rn += ">"; if (nLevel == 0) { Rn += "│ ├"; } else { string _f = ""; for (int i = 1; i <= nLevel; i++) { _f += "│ "; } Rn += _f + "│ ├"; } Rn += fInfo.Name.ToString() + "</option>"; } Rn = ListTreeShow(dirinfo, nLevel + 1, Rn, tplPath); } return Rn; } #endregion #region 获取文件夹大小 /**************************************** * 函数名称:GetDirectoryLength(string dirPath) * 功能说明:获取文件夹大小 * 参 数:dirPath:文件夹详细路径 * 调用示列: * string Path = Server.MapPath("templates"); * Response.Write(EC.FileObj.GetDirectoryLength(Path)); *****************************************/ /// <summary> /// 获取文件夹大小 /// </summary> /// <param name="dirPath">文件夹路径</param> /// <returns></returns> public static long GetDirectoryLength(string 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; } #endregion #region 获取指定文件详细属性 /**************************************** * 函数名称:GetFileAttibe(string filePath) * 功能说明:获取指定文件详细属性 * 参 数:filePath:文件详细路径 * 调用示列: * string file = Server.MapPath("robots.txt"); * Response.Write(EC.FileObj.GetFileAttibe(file)); *****************************************/ /// <summary> /// 获取指定文件详细属性 /// </summary> /// <param name="filePath">文件详细路径</param> /// <returns></returns> public static string GetFileAttibe(string filePath) { string str = ""; System.IO.FileInfo objFI = new System.IO.FileInfo(filePath); str += "详细路径:" + objFI.FullName + "<br>文件名称:" + objFI.Name + "<br>文件长度:" + objFI.Length.ToString() + "字节<br>创建时间" + objFI.CreationTime.ToString() + "<br>最后访问时间:" + objFI.LastAccessTime.ToString() + "<br>修改时间:" + objFI.LastWriteTime.ToString() + "<br>所在目录:" + objFI.DirectoryName + "<br>扩展名:" + objFI.Extension; return str; } #endregion #region 上传图片并且按比例生成缩略图 /// <summary> /// 上传图片并且生成缩略图,eg:UpLoadFile(uploadFile, ".jpg|.gif|.bmp", 500,200, Server.MapPath("./Uploads/"), 1, true,out newFileName) /// </summary> /// <param name="fu">上传文件</param> /// <param name="type">上传文件类型,例如.jpg|.gif|.bmp</param> /// <param name="size">限制上传文件大小,单位为k</param> /// <param name="picZoolSize">缩略图缩放大小,例如:200 表示200px</param> /// <param name="path">上传路径,需使用server.mappath</param> /// <param name="nametype">1为自动命名,0用原名</param> /// <param name="flag">是否生成缩略图</param> /// <returns></returns> public static string UpLoadFile(FileUpload fu, string type, int size, int picZoolSize, string path, int nametype, bool flag, out string newFileName) { newFileName = null; string erorr = null; int Size = fu.PostedFile.ContentLength / 1024; if (Size > size) { erorr = "上传文件太大!"; return erorr; } string Type = fu.FileName; if (Type.IndexOf(".") == -1) { erorr = "上传文件类型有误!确认文件后缀名为jpg或gif或bmp"; return erorr; } Type = Type.Substring(Type.LastIndexOf(".")).ToUpper(); type = type.ToUpper(); if (type.IndexOf(Type) == -1) { erorr = "上传文件类型有误!确认文件后缀名为jpg或gif或bmp"; return erorr; } string filename = ""; if (nametype == 1) { string nowdate = DateTime.Now.ToString(); nowdate = nowdate.Replace(":", "").Replace(" ", "").Replace("-", "").Trim(); Random r = new Random(); int a = r.Next(1000); filename = nowdate + a.ToString() + Type; newFileName = filename; } else { filename = fu.FileName; if (System.IO.File.Exists(path + filename)) { erorr = "此文件名已经存在!"; return erorr; } } fu.SaveAs(path + filename); //生成缩略开始 if (flag) { System.Drawing.Image image, aNewImage; int width, height, newwidth, newheight; System.Drawing.Image.GetThumbnailImageAbort callb = null; image = System.Drawing.Image.FromFile(path + filename); width = image.Width; height = image.Height; if (width > height) { newwidth = picZoolSize; newheight = picZoolSize * height / width; } else { newheight = picZoolSize; newwidth = picZoolSize * width / height; } aNewImage = image.GetThumbnailImage(newwidth, newheight, callb, new System.IntPtr()); aNewImage.Save(path + "S_" + filename); image.Dispose(); } //生成缩略结束 //fname = filename; return erorr;//返回有错的错误信息,没有错误返回null } #endregion #region 判断上传文件是否为图片 /// <summary> /// 判断上传文件是否是图片 /// </summary> /// <param name="strFileName">文件名,eg:this.FileUpload1.FileName</param> /// <returns></returns> public static bool isImage(string strFileName) { if (strFileName != "") { strFileName = (System.IO.Path.GetFileName(strFileName)).ToLower(); string[] strExt = new string[7]; strExt[0] = ".gif"; strExt[1] = ".jpg"; strExt[2] = ".jpeg"; strExt[3] = ".jpe"; strExt[4] = ".bmp"; strExt[5] = ".png"; strExt[6] = ".tif"; string strExtensions = System.IO.Path.GetExtension(strFileName); if (Array.IndexOf(strExt, strExtensions) == -1 && strFileName != "") return false; else return true; } else { return false; } } #endregion #region 下载文件,提供两种方法下载 /// <summary> /// 简单的文件下载方法,利用微软提供新的方法TransmitFile来解决下载超过400mb的文件时问题 /// </summary> /// <param name="contentType">文件类型 例如image/gif</param> /// <param name="filePath">文件路径 例如Server.MapPath("20051515251748.gif")</param> public static void DownFile(string contentType, string filePath) { /* 微软为Response对象提供了一个新的方法TransmitFile来解决使用Response.BinaryWrite 下载超过400mb的文件时导致Aspnet_wp.exe进程回收而无法成功下载的问题。 代码如下: */ string fileName = filePath.Substring(filePath.LastIndexOf('\\') + 1); HttpContext.Current.Response.ContentType = contentType; //让所有文件直接下载而不是在浏览器打开 HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); HttpContext.Current.Response.TransmitFile(filePath); } /// <summary> /// 输出硬盘文件,提供下载 支持大文件、续传、速度限制、资源占用小 /// <code> /// string FullPath=Server.MapPath("count.txt"); /// ResponseFile(this.Request,this.Response,"count.txt",FullPath,100); /// </code> /// </summary> /// <param name="_Request">Page.Request对象</param> /// <param name="_Response">Page.Response对象</param> /// <param name="_fileName">保存在本机的下载文件名 例如 "TB_CellInfo.xls"</param> /// <param name="_fullPath">带文件名下载路径 例如Server.MapPath("~/DownloadFiles/") + "TB_CellInfo.xls"</param> /// <param name="_speed">每秒允许下载的字节数</param> /// <returns>返回是否成功</returns> public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed) { try { FileStream myFile = new FileStream(_fullPath, 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; double pack = 10240; //10K bytes //int sleep = 200; //每秒5次 即5*10K bytes每秒 int sleep = (int)Math.Floor(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((fileLength - startBytes) / pack) + 1; for (int i = 0; i < maxCount; i++) { if (_Response.IsClientConnected) { _Response.BinaryWrite(br.ReadBytes(int.Parse(pack.ToString()))); Thread.Sleep(sleep); } else { i = maxCount; } } } catch { return false; } finally { br.Close(); myFile.Close(); } } catch { return false; } return true; } #endregion } }
时间: 2024-10-29 15:51:51