命名空間:namespace System.IO.Compressionjavascript
壓縮:html
//目標文件夾 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");
解壓:java
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
//得到目錄下全部文件和子目錄 使用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; 壓縮文件緩存
/// <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.htmlapp
http://www.cnblogs.com/ForRickHuan/p/7348221.htmlide
複製文件夾:this
/// <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(); } }
文件屬性:加密
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.htmlspa
//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.htmlcode
zip文件的建立、讀寫和更新: http://www.cnblogs.com/tcjiaan/p/4877020.html
動態生成zip文件: http://www.cnblogs.com/tcjiaan/p/4892578.html