C# 压缩 解压 复制文件夹,文件的操作
命名空间:namespace System.IO.Compression
压缩:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//目标文件夹 string fileDirPath = "/Downloads/试题" + userId + "_" + courseId; string downPath = Server.MapPath(fileDirPath); if (!Directory.Exists(downPath)) { Directory.CreateDirectory(downPath); } System.IO.File.SetAttributes(downPath, FileAttributes.Normal); //压缩文件 string filePathZIP = Server.MapPath(fileDirPath) + ".zip"; //压缩文件夹 if (System.IO.File.Exists(filePathZIP)) { System.IO.File.Delete(filePathZIP); } System.IO.File.SetAttributes(downPath, FileAttributes.Normal); ZipFile.CreateFromDirectory(downPath, filePathZIP, CompressionLevel.Optimal, true);//压缩文件 if (System.IO.Directory.Exists(downPath)) { System.IO.Directory.Delete(downPath, true); //删除原文件夹 } return File(filePathZIP, "application/octet-stream", "试题" + "_" + userId + "_" + courseId + ".zip");
解压:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
HttpPostedFileBase fileBase = Request.Files["fileImport"]; string fileName = Path.GetFileName(fileBase.FileName); string fileNameNoExt = Path.GetFileNameWithoutExtension(fileBase.FileName); string extension = Path.GetExtension(fileName); if (extension.ToLower() != ".zip") //extension.ToLower() != ".xls" || extension.ToLower() != ".xlsx" || { //window.location.href='@Url.Action('CoursePackManage','ManageCourse')' window.location.href='/admin/ManageCourse/CoursePackManage'; return Content("<script type='text/javascript'>alert('请上传zip格式的压缩文件');window.location.href='/admin/ManageCourse/CoursePackManage';</script>"); } string filePath = "/UploadFile/试题/"; // +DateTime.Now.ToString("yyyyMMdd") + "/"; if (!Directory.Exists(Server.MapPath(filePath))) //文件夹 { Directory.CreateDirectory(Server.MapPath(filePath)); } string nowTime = DateTime.Now.ToString("yyyyMMddHHmmssfff"); string fullFileName = Server.MapPath(filePath + nowTime + "_" + userId + "_" + courseId + "_" + fileName);//文件名 fileBase.SaveAs(fullFileName); #region 压缩包 if (extension.ToLower() == ".zip") { string destFilePath = Server.MapPath(filePath + nowTime + "_" + userId + "_" + courseId + "_" + fileNameNoExt); //不带后缀文件名字 if (!Directory.Exists(destFilePath)) //文件夹 { Directory.CreateDirectory(destFilePath); } ZipFile.ExtractToDirectory(fullFileName, destFilePath, Encoding.Default); //解压文件 System.IO.File.Delete(fullFileName);//解压后删除文件 #region 复制文件夹 DirectoryInfo sourceDir = new System.IO.DirectoryInfo(destFilePath); //处理文件夹 foreach (var item in sourceDir.GetDirectories()) //一级目录 { foreach (var childDir in item.GetDirectories()) //二级目录 { if (childDirName.Equals("文件夹名", StringComparison.CurrentCultureIgnoreCase)) { CopyDirectory(childFullName, destDirName); //复制文件夹 } } } #endregion } #endregion
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//获得目录下所有文件和子目录 使用DirectoryInfo类的GetFileSystemInfos()方法。 //获得目录下所有目录 string[] dirs = Directory.GetDirectories(你的目录的完整路径, "*", SearchOption.AllDirectories); //获得目录下所有文件(包括该目录下的子目录的文件) string[] dirs1 = Directory.GetFiles(你的目录的完整路径, "*.*", SearchOption.AllDirectories); //该目录下的子目录和文件 var fileEntrys = System.IO.Directory.GetFileSystemEntries(filePath); //获得一个目录下所有文件 string[] strNames = Directory.GetFiles(你的目录的完整路径);
using ICSharpCode.SharpZipLib.Zip; 压缩文件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/// <summary> /// ZIP压缩单个文件 /// </summary> /// <param name="sFileToZip">需要压缩的文件(绝对路径)</param> /// <param name="sZippedPath">压缩后的文件路径(绝对路径)</param> /// <param name="sZippedFileName">压缩后的文件名称(文件名,默认 同源文件同名)</param> /// <param name="nCompressionLevel">压缩等级(0 无 - 9 最高,默认 5)</param> /// <param name="nBufferSize">缓存大小(每次写入文件大小,默认 2048)</param> /// <param name="bEncrypt">是否加密(默认 加密)</param> /// <param name="sPassword">密码(设置加密时生效。默认密码为"123")</param> public static string ZipFile(string sFileToZip, string sZippedPath, string sZippedFileName = "", int nCompressionLevel = 5, int nBufferSize = 2048, bool bEncrypt = true,string sPassword="123") { if (!File.Exists(sFileToZip)) { return null; } string sZipFileName = string.IsNullOrEmpty(sZippedFileName) ? sZippedPath + "\\" + new FileInfo(sFileToZip).Name.Substring(0, new FileInfo(sFileToZip).Name.LastIndexOf('.')) + ".zip" : sZippedPath + "\\" + sZippedFileName + ".zip"; using (FileStream aZipFile = File.Create(sZipFileName)) { using (ZipOutputStream aZipStream = new ZipOutputStream(aZipFile)) { using (FileStream aStreamToZip = new FileStream(sFileToZip, FileMode.Open, FileAccess.Read)) { string sFileName = sFileToZip.Substring(sFileToZip.LastIndexOf("\\") + 1); ZipEntry ZipEntry = new ZipEntry(sFileName); if (bEncrypt) { aZipStream.Password = sPassword; } aZipStream.PutNextEntry(ZipEntry); aZipStream.SetLevel(nCompressionLevel); byte[] buffer = new byte[nBufferSize]; int sizeRead = 0; try { do { sizeRead = aStreamToZip.Read(buffer, 0, buffer.Length); aZipStream.Write(buffer, 0, sizeRead); } while (sizeRead > 0); } catch (Exception ex) { throw ex; } aStreamToZip.Close(); } aZipStream.Finish(); aZipStream.Close(); } aZipFile.Close(); } return sZipFileName; }
https://www.cnblogs.com/xuhongfei/p/5604193.html
http://www.cnblogs.com/ForRickHuan/p/7348221.html
复制文件夹:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/// <summary> /// 复制文件夹 /// </summary> /// <param name="sourceDirName">源文件</param> /// <param name="destDirName">目标文件</param> private void CopyDirectory(string sourceDirName, string destDirName) { try { if (!Directory.Exists(destDirName)) { Directory.CreateDirectory(destDirName); System.IO.File.SetAttributes(destDirName, System.IO.File.GetAttributes(sourceDirName)); } if (destDirName[destDirName.Length - 1] != Path.DirectorySeparatorChar) // =="\\" { destDirName = destDirName + Path.DirectorySeparatorChar; } string[] files = Directory.GetFiles(sourceDirName); foreach (string file in files) { if (System.IO.File.Exists(destDirName + Path.GetFileName(file))) continue; System.IO.File.Copy(file, destDirName + Path.GetFileName(file), true); System.IO.File.SetAttributes(destDirName + Path.GetFileName(file), FileAttributes.Normal); //total++; } string[] dirs = Directory.GetDirectories(sourceDirName);//包括路径 foreach (string dir in dirs) { CopyDirectory(dir, destDirName + Path.GetFileName(dir)); } } catch (Exception ex) { //StreamWriter sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\log.txt", true); //System.Web.Providers.Entities //sw.Write(ex.Message + " " + DateTime.Now + "\r\n"); //sw.Close(); } }
文件属性:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
C#遍历指定文件夹中的所有文件 DirectoryInfo TheFolder=new DirectoryInfo(folderFullName); //遍历文件夹 foreach(DirectoryInfo NextFolder in TheFolder.GetDirectories()) this.listBox1.Items.Add(NextFolder.Name); //遍历文件 foreach(FileInfo NextFile in TheFolder.GetFiles()) this.listBox2.Items.Add(NextFile.Name); =================================================================== 如何获取指定目录包含的文件和子目录 1. DirectoryInfo.GetFiles():获取目录中(不包含子目录)的文件,返回类型为FileInfo[],支持通配符查找; 2. DirectoryInfo.GetDirectories():获取目录(不包含子目录)的子目录,返回类型为DirectoryInfo[],支持通配符查找; 3. DirectoryInfo. GetFileSystemInfos():获取指定目录下(不包含子目录)的文件和子目录,返回类型为FileSystemInfo[],支持通配符查找; 如何获取指定文件的基本信息; FileInfo.Exists:获取指定文件是否存在; FileInfo.Name,FileInfo.Extensioin:获取文件的名称和扩展名; FileInfo.FullName:获取文件的全限定名称(完整路径); FileInfo.Directory:获取文件所在目录,返回类型为DirectoryInfo; FileInfo.DirectoryName:获取文件所在目录的路径(完整路径); FileInfo.Length:获取文件的大小(字节数); FileInfo.IsReadOnly:获取文件是否只读; FileInfo.Attributes:获取或设置指定文件的属性,返回类型为FileAttributes枚举,可以是多个值的组合 FileInfo.CreationTime、FileInfo.LastAccessTime、FileInfo.LastWriteTime:分别用于获取文件的创建时间、访问时间、修改时间;
C#文件及文件夹操作示例 http://www.cnblogs.com/terer/articles/1514601.html
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//1.---------文件夹创建、移动、删除--------- //创建文件夹 Directory.CreateDirectory(Server.MapPath("a")); Directory.CreateDirectory(Server.MapPath("b")); Directory.CreateDirectory(Server.MapPath("c")); //移动b到a Directory.Move(Server.MapPath("b"), Server.MapPath("a\\b")); //删除c Directory.Delete(Server.MapPath("c")); //2.---------文件创建、复制、移动、删除--------- //创建文件 //使用File.Create创建再复制/移动/删除时会提示:文件正由另一进程使用,因此该进程无法访问该文件 //改用 FileStream 获取 File.Create 返回的 System.IO.FileStream 再进行关闭就无此问题 FileStream fs; fs = File.Create(Server.MapPath("a.txt")); fs.Close(); fs = File.Create(Server.MapPath("b.txt")); fs.Close(); fs = File.Create(Server.MapPath("c.txt")); fs.Close(); //复制文件 File.Copy(Server.MapPath("a.txt"), Server.MapPath("a\\a.txt")); //移动文件 File.Move(Server.MapPath("b.txt"), Server.MapPath("a\\b.txt")); File.Move(Server.MapPath("c.txt"), Server.MapPath("a\\c.txt")); //删除文件 File.Delete(Server.MapPath("a.txt")); //3.---------遍历文件夹中的文件和子文件夹并显示其属性--------- if(Directory.Exists(Server.MapPath("a"))) { //所有子文件夹 foreach(string item in Directory.GetDirectories(Server.MapPath("a"))) { Response.Write("<b>文件夹:" + item + "</b><br/>"); DirectoryInfo directoryinfo = new DirectoryInfo(item); Response.Write("名称:" + directoryinfo.Name + "<br/>"); Response.Write("路径:" + directoryinfo.FullName + "<br/>"); Response.Write("创建时间:" + directoryinfo.CreationTime + "<br/>"); Response.Write("上次访问时间:" + directoryinfo.LastAccessTime + "<br/>"); Response.Write("上次修改时间:" + directoryinfo.LastWriteTime + "<br/>"); Response.Write("父文件夹:" + directoryinfo.Parent + "<br/>"); Response.Write("所在根目录:" + directoryinfo.Root + "<br/>"); Response.Write("<br/>"); } //所有子文件 foreach (string item in Directory.GetFiles(Server.MapPath("a"))) { Response.Write("<b>文件:" + item + "</b><br/>"); FileInfo fileinfo = new FileInfo(item); Response.Write("名称:" + fileinfo.Name + "<br/>"); Response.Write("扩展名:" + fileinfo.Extension +"<br/>"); Response.Write("路径:" + fileinfo.FullName +"<br/>"); Response.Write("大小:" + fileinfo.Length +"<br/>"); Response.Write("创建时间:" + fileinfo.CreationTime +"<br/>"); Response.Write("上次访问时间:" + fileinfo.LastAccessTime +"<br/>"); Response.Write("上次修改时间:" + fileinfo.LastWriteTime +"<br/>"); Response.Write("所在文件夹:" + fileinfo.DirectoryName +"<br/>"); Response.Write("文件属性:" + fileinfo.Attributes +"<br/>"); Response.Write("<br/>"); } } //4.---------文件读写--------- if (File.Exists(Server.MapPath("a\\a.txt"))) { StreamWriter streamwrite = new StreamWriter(Server.MapPath("a\\a.txt")); streamwrite.WriteLine("木子屋"); streamwrite.WriteLine("http://www.mzwu.com/"); streamwrite.Write("2008-04-13"); streamwrite.Close(); StreamReader streamreader = new StreamReader(Server.MapPath("a\\a.txt")); Response.Write(streamreader.ReadLine()); Response.Write(streamreader.ReadToEnd()); streamreader.Close(); }
C#操作目录和文件 http://www.cnblogs.com/wanghonghu/archive/2012/07/04/2574579.html
zip文件的创建、读写和更新: http://www.cnblogs.com/tcjiaan/p/4877020.html
动态生成zip文件: http://www.cnblogs.com/tcjiaan/p/4892578.html