public static void UnZipFiles(string zipPathAndFile, string outputFolder) { var s = new ZipInputStream(File.OpenRead(zipPathAndFile)); ZipEntry theEntry; var tmpEntry = String.Empty; while ((theEntry = s.GetNextEntry()) != null) { var directoryName = outputFolder; var fileName = Path.GetFileName(theEntry.Name); if (directoryName != "") Directory.CreateDirectory(directoryName); if (fileName != String.Empty) if (theEntry.Name.IndexOf(".ini") < 0) { var fullPath = directoryName + "\\" + theEntry.Name; fullPath = fullPath.Replace("\\ ", "\\"); string fullDirPath = Path.GetDirectoryName(fullPath); if (!Directory.Exists(fullDirPath)) Directory.CreateDirectory(fullDirPath); FileStream streamWriter = File.Create(fullPath); int size = 2048; byte[] data = new byte[2048]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) streamWriter.Write(data, 0, size); else break; } streamWriter.Close(); } } s.Close(); File.Delete(zipPathAndFile); }
/// <summary> /// 압축 파일 풀기 /// </summary> /// <param name="zipFilePath">ZIP파일 경로</param> /// <param name="unZipTargetFolderPath">압축 풀 폴더 경로</param> /// <param name="password">해지 암호</param> /// <param name="isDeleteZipFile">zip파일 삭제 여부</param> /// <returns>압축 풀기 성공 여부 </returns> public static bool UnZipFiles(string zipFilePath, string unZipTargetFolderPath, string password, bool isDeleteZipFile) { bool retVal = false; // ZIP 파일이 있는 경우만 수행. if (File.Exists(zipFilePath)) { // ZIP 스트림 생성. ZipInputStream zipInputStream = new ZipInputStream(File.OpenRead(zipFilePath)); // 패스워드가 있는 경우 패스워드 지정. if (password != null && password != String.Empty) { zipInputStream.Password = password; } try { ZipEntry theEntry; // 반복하며 파일을 가져옴. while ((theEntry = zipInputStream.GetNextEntry()) != null) { // 폴더 string directoryName = Path.GetDirectoryName(theEntry.Name); string fileName = Path.GetFileName(theEntry.Name); // 파일 // 폴더 생성 Directory.CreateDirectory(unZipTargetFolderPath + directoryName); // 파일 이름이 있는 경우 if (fileName != String.Empty) { // 파일 스트림 생성.(파일생성) FileStream streamWriter = File.Create((unZipTargetFolderPath + theEntry.Name)); int size = 2048; byte[] data = new byte[2048]; // 파일 복사 while (true) { size = zipInputStream.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } // 파일스트림 종료 streamWriter.Close(); } } retVal = true; } catch { retVal = false; } finally { // ZIP 파일 스트림 종료 zipInputStream.Close(); } // ZIP파일 삭제를 원할 경우 파일 삭제. if (isDeleteZipFile) { try { File.Delete(zipFilePath); } catch { } } } return(retVal); }
private void buttonItem5_Click(object sender, EventArgs e) { string helpPath = Common.TempPath + "\\SAS_help.htm"; if (File.Exists(helpPath)) { System.Diagnostics.Process.Start(helpPath); } else { //FileStream fs = new FileStream(help, FileMode.OpenOrCreate, FileAccess.Write); ////创建byte数组,装资源 //Byte[] b = DMS.Properties.Resources.help; //fs.Write(b, 0, b.Length); //if (fs != null) // fs.Close(); try { Stream S = new MemoryStream(SAS.Properties.Resources.SAS_Help); //using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath))) string rootFile = ""; string fileDir = Common.TempPath; //读取压缩文件(zip文件),准备解压缩 ZipInputStream s = new ZipInputStream(S); ZipEntry theEntry; string path = fileDir; //解压出来的文件保存的路径 string rootDir = ""; //根目录下的第一个子文件夹的名称 while ((theEntry = s.GetNextEntry()) != null) { rootDir = Path.GetDirectoryName(theEntry.Name); //得到根目录下的第一级子文件夹的名称 if (rootDir.IndexOf("\\") >= 0) { rootDir = rootDir.Substring(0, rootDir.IndexOf("\\") + 1); } string dir = Path.GetDirectoryName(theEntry.Name); //根目录下的第一级子文件夹的下的文件夹的名称 string fileName = Path.GetFileName(theEntry.Name); //根目录下的文件名称 if (dir != "" && fileName == "") //创建根目录下的子文件夹,不限制级别 { if (!Directory.Exists(fileDir + "\\" + dir)) { path = fileDir + "\\" + dir; //在指定的路径创建文件夹 Directory.CreateDirectory(path); } } else if (dir == "" && fileName != "") //根目录下的文件 { path = fileDir; rootFile = fileName; } else if (dir != "" && fileName != "") //根目录下的第一级子文件夹下的文件 { if (dir.IndexOf("\\") > 0) //指定文件保存的路径 { path = fileDir + "\\" + dir; } } if (dir == rootDir) //判断是不是需要保存在根目录下的文件 { path = fileDir + "\\" + rootDir; } //以下为解压缩zip文件的基本步骤 //基本思路就是遍历压缩文件里的所有文件,创建一个相同的文件。 if (fileName != String.Empty) { FileStream streamWriter = File.Create(path + "\\" + fileName); int size = 2048; byte[] data = new byte[2048]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } streamWriter.Close(); //streamWriter.Dispose(); } } s.Close(); System.Diagnostics.Process.Start(helpPath); } catch (Exception ex) { MessageBox.Show(ex.Message); } GC.Collect(); } }
/// <summary> /// Decompress a zip compatible archive /// </summary> /// <param name="destinationDirectory">the directory where the files should be decompressed</param> /// <param name="myzipfile">the zip file to decompress</param> /// <returns>true if success</returns> /// <remarks></remarks> public static bool Decompress(string destinationDirectory, string myzipfile) { //Decompress zip archive in DestinationDirectory //Example: decompression("c:/DossierResultat", "c:/Dossier.zip") try { // Create zipstream ZipInputStream zipIStream = new ZipInputStream(File.OpenRead(myzipfile)); // For all entry's while (true) { // Read next entry ZipEntry theEntry = zipIStream.GetNextEntry(); if (theEntry == null) { break; } //end when done // check if file if (!theEntry.IsFile) { continue; } // Define zipfile FileInfo myFile = new FileInfo(destinationDirectory + "/" + theEntry.Name); if (myFile.Directory == null) { continue; } // Create directory if (!myFile.Directory.Exists) { myFile.Directory.Create(); } // Create end file FileStream fs = new FileStream(myFile.FullName, FileMode.Create); int size = 2048; byte[] data = new byte[size + 1]; while (!((size <= 0))) { size = zipIStream.Read(data, 0, data.Length); fs.Write(data, 0, size); } fs.Flush(); fs.Close(); } // Close stream zipIStream.Close(); return(true); } catch (Exception ex) { Logger.Log(LogLevel.Severe, "Compression", "Error while decompressing files!", ex.Message); return(false); } }
/// <summary> /// 解压缩一个 zip 文件。 /// </summary> /// <param name="zipedFile">The ziped file.</param> /// <param name="strDirectory">The STR directory.</param> /// <param name="password">zip 文件的密码。</param> /// <param name="overWrite">是否覆盖已存在的文件。</param> public void UnZip(string zipedFile, string strDirectory, string password, bool overWrite) { if (strDirectory == "") { strDirectory = Directory.GetCurrentDirectory(); } if (!strDirectory.EndsWith("\\")) { strDirectory = strDirectory + "\\"; } using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipedFile))) { s.Password = password; ZipEntry theEntry; while ((theEntry = s.GetNextEntry()) != null) { string directoryName = ""; string pathToZip = ""; pathToZip = theEntry.Name; if (pathToZip != "") { directoryName = Path.GetDirectoryName(pathToZip) + "\\"; } string fileName = Path.GetFileName(pathToZip); Directory.CreateDirectory(strDirectory + directoryName); if (fileName != "") { if ((File.Exists(strDirectory + directoryName + fileName) && overWrite) || (!File.Exists(strDirectory + directoryName + fileName))) { using (FileStream streamWriter = File.Create(strDirectory + directoryName + fileName)) { int size = 2048; byte[] data = new byte[2048]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } streamWriter.Close(); } } } } s.Close(); } }
public static void UnZipFiles(string zipPathAndFile, string outputFolder, string password, bool deleteZipFile, bool ignoreFolderNames) { ZipInputStream s = new ZipInputStream(File.OpenRead(zipPathAndFile)); if (!string.IsNullOrEmpty(password)) { s.Password = password; } ZipEntry theEntry; while ((theEntry = s.GetNextEntry()) != null) { string directoryName = outputFolder; string fileName = Path.GetFileName(theEntry.Name); // create directory if (directoryName != "") { Directory.CreateDirectory(directoryName); } if (fileName != String.Empty) { if (theEntry.Name.IndexOf(".ini") < 0) { string fullPath; if (ignoreFolderNames) { fullPath = Path.Combine(directoryName, fileName); } else { fullPath = Path.Combine(directoryName, theEntry.Name); } fullPath = fullPath.Replace("\\ ", "\\"); string fullDirPath = Path.GetDirectoryName(fullPath); if (!Directory.Exists(fullDirPath)) { Directory.CreateDirectory(fullDirPath); } FileStream streamWriter = File.Create(fullPath); int size = 2048; byte[] data = new byte[2048]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } streamWriter.Close(); } } } s.Close(); if (deleteZipFile) { File.Delete(zipPathAndFile); } }
/// <summary> /// Unpacks the specified source path. /// </summary> /// <param name="sourcePath">The source path.</param> /// <param name="ignoreInvalidHeaders">if set to <c>true</c> [ignore invalid headers].</param> /// <returns></returns> /// <remarks>Documented by Dev03, 2007-09-11</remarks> public IDictionary Unpack(string sourcePath, bool ignoreInvalidHeaders) { string dictionaryPath = String.Empty; //ZipConstants.DefaultCodePage = Encoding.Unicode.CodePage; //this may possibly mean that we are not Zip compatible anymore using (FileStream sourceStream = File.OpenRead(sourcePath)) { string temporaryPath; if (!ignoreInvalidHeaders) { // Checking Zip File Header if (!IsValidArchive(sourcePath)) { throw new NoValidArchiveException(); } } long zipFileSize = 0; ZipFile zipFile = null; try { zipFile = new ZipFile(sourcePath); zipFileSize = zipFile.Count; } catch (Exception ex) { throw ex; } finally { if (zipFile != null) { zipFile.Close(); } } if (m_temporaryFolder.Length == 0) { temporaryPath = Path.GetTempPath(); temporaryPath = Path.Combine(temporaryPath, Path.GetRandomFileName()); } else { temporaryPath = m_temporaryFolder; } if (!Directory.Exists(temporaryPath)) { Directory.CreateDirectory(temporaryPath); } System.IO.Directory.SetCurrentDirectory(temporaryPath); // Extract files ZipInputStream zipStream = new ZipInputStream(sourceStream); ZipEntry zipEntry; int nBytes = 2048; byte[] data = new byte[nBytes]; int counter = 1; if (!ReportProgressUpdate(0)) { return(null); } while ((zipEntry = zipStream.GetNextEntry()) != null) { if (!Directory.Exists(Path.GetDirectoryName(Path.Combine(temporaryPath, zipEntry.Name)))) { Directory.CreateDirectory(Path.GetDirectoryName(Path.Combine(temporaryPath, zipEntry.Name))); } if (Path.GetExtension(zipEntry.Name).ToLower() == Resources.DICTIONARY_ODX_EXTENSION) { dictionaryPath = Path.Combine(temporaryPath, zipEntry.Name); } // write file try { string filePath = Path.Combine(temporaryPath, zipEntry.Name); FileMode fileMode = (File.Exists(filePath)) ? FileMode.Truncate : FileMode.OpenOrCreate; using (FileStream writer = new FileStream(filePath, fileMode, FileAccess.ReadWrite, FileShare.Read)) { while ((nBytes = zipStream.Read(data, 0, data.Length)) > 0) { writer.Write(data, 0, nBytes); } } } catch (Exception ex) { Debug.WriteLine("DAL.Pack.Unpack() - " + zipEntry.Name + " - " + ex.Message); if (zipEntry.Name.Contains(DAL.Helper.OdxExtension)) { throw ex; } } int progress = (int)Math.Floor(100.0 * (counter++) / zipFileSize); if (!ReportProgressUpdate(progress)) { return(null); } } if (!ReportProgressUpdate(100)) { return(null); } zipStream.Close(); sourceStream.Close(); } if (dictionaryPath.Length == 0) { throw new NoValidArchiveException(); } return(UserFactory.Create(m_loginCallback, new ConnectionStringStruct(DatabaseType.Xml, dictionaryPath, true), (DataAccessErrorDelegate) delegate { return; }, this).Open()); }
public void MixedEncryptedAndPlain() { var compressedData = MakeInMemoryZip(true, new RuntimeInfo(CompressionMethod.Deflated, 2, 1, null, true), new RuntimeInfo(CompressionMethod.Deflated, 9, 1, "1234", false), new RuntimeInfo(CompressionMethod.Deflated, 2, 1, null, false), new RuntimeInfo(CompressionMethod.Deflated, 9, 1, "1234", true) ); var ms = new MemoryStream(compressedData); using (var inStream = new ZipInputStream(ms)) { inStream.Password = "******"; var extractCount = 0; var extractIndex = 0; ZipEntry entry; var decompressedData = new byte[100]; while ((entry = inStream.GetNextEntry()) != null) { extractCount = decompressedData.Length; extractIndex = 0; while (true) { var numRead = inStream.Read(decompressedData, extractIndex, extractCount); if (numRead <= 0) { break; } extractIndex += numRead; extractCount -= numRead; } } inStream.Close(); } }
/// 解压缩一个 zip 文件。 /// The ziped file. /// The STR directory. /// zip 文件的密码。 /// 是否覆盖已存在的文件。 public static bool UnZip(string zipedFile, string strDirectory, string password, bool overWrite) { zipedFile = zipedFile.Replace("\\", "/"); strDirectory = strDirectory.Replace("\\", "/"); if (strDirectory == "") { strDirectory = Directory.GetCurrentDirectory(); } if (!strDirectory.EndsWith("/")) { strDirectory = strDirectory + "/"; } try { using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipedFile))) { s.Password = password; ZipEntry theEntry; while ((theEntry = s.GetNextEntry()) != null) { string directoryName = ""; string pathToZip = ""; pathToZip = theEntry.Name; if (pathToZip != "") { directoryName = Path.GetDirectoryName(pathToZip) + "/"; } string fileName = Path.GetFileName(pathToZip); Directory.CreateDirectory(strDirectory + directoryName); if (fileName != "") { if ((File.Exists(strDirectory + directoryName + fileName) && overWrite) || (!File.Exists(strDirectory + directoryName + fileName))) { using (FileStream streamWriter = File.Create(strDirectory + directoryName + fileName)) { int size = 2048; byte[] data = new byte[2048]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } streamWriter.Close(); } } } } s.Close(); return(true); } } catch (Exception ex) { LogUtil.E("解压文件{0}失败:{1}", zipedFile, ex); return(false); } }
public string GetPackageNameFromZip(string fullpathpackagefilename, out string packageversion) { if (string.IsNullOrEmpty(fullpathpackagefilename))//no package name is provided { packageversion = "0.0-0"; return("nopackagename"); } string packagename = string.Empty; packageversion = string.Empty; //to get the version FileStream fileStreamIn = new FileStream(fullpathpackagefilename, FileMode.Open, FileAccess.Read); //to fix the exception 'if' block is added above ZipInputStream zipInStream = new ZipInputStream(fileStreamIn); ZipEntry entry = zipInStream.GetNextEntry(); string tempDir = Path.GetTempPath().Replace("\\", "/"); StringBuilder path = new StringBuilder(tempDir); path.Append("DESCRIPTION"); FileStream fileStreamOut = null; bool isFileExtracted = false; //Extract the file while (entry != null) { if (entry.Name.EndsWith("DESCRIPTION")) { fileStreamOut = new FileStream(path.ToString(), FileMode.Create, FileAccess.Write); int size; byte[] buffer = new byte[1024]; do { size = zipInStream.Read(buffer, 0, buffer.Length); fileStreamOut.Write(buffer, 0, size); } while (size > 0); fileStreamOut.Close(); isFileExtracted = true; break; } entry = zipInStream.GetNextEntry(); } zipInStream.Close(); fileStreamIn.Close(); //Read Line by line if (isFileExtracted) { string line; System.IO.StreamReader file = new System.IO.StreamReader(path.ToString()); while ((line = file.ReadLine()) != null) { if (line.Contains("Package:")) { packagename = line.Replace("Package:", string.Empty).Trim(); //break; } if (line.Contains("Version:")) { packageversion = line.Replace("Version:", string.Empty).Trim(); break; } } file.Close(); } return(packagename); }
/// ----------------------------------------------------------------------------- /// <summary> /// The InstallFile method installs a single assembly. /// </summary> /// <param name = "insFile">The InstallFile to install</param> protected override bool InstallFile(InstallFile insFile) { FileStream fs = null; ZipInputStream unzip = null; XmlWriter writer = null; bool retValue = true; try { Log.AddInfo(Util.FILES_Expanding); unzip = new ZipInputStream(new FileStream(insFile.TempFileName, FileMode.Open)); //Create a writer to create the manifest for the resource file _Manifest = insFile.Name + ".manifest"; if (!Directory.Exists(PhysicalBasePath)) { Directory.CreateDirectory(PhysicalBasePath); } fs = new FileStream(Path.Combine(PhysicalBasePath, Manifest), FileMode.Create, FileAccess.Write); var settings = new XmlWriterSettings(); settings.ConformanceLevel = ConformanceLevel.Fragment; settings.OmitXmlDeclaration = true; settings.Indent = true; writer = XmlWriter.Create(fs, settings); //Start the new Root Element writer.WriteStartElement("dotnetnuke"); writer.WriteAttributeString("type", "ResourceFile"); writer.WriteAttributeString("version", "5.0"); //Start files Element writer.WriteStartElement("files"); ZipEntry entry = unzip.GetNextEntry(); while (entry != null) { if (!entry.IsDirectory) { string fileName = Path.GetFileName(entry.Name); //Start file Element writer.WriteStartElement("file"); //Write path writer.WriteElementString("path", entry.Name.Substring(0, entry.Name.IndexOf(fileName))); //Write name writer.WriteElementString("name", fileName); string physicalPath = Path.Combine(PhysicalBasePath, entry.Name); if (File.Exists(physicalPath)) { Util.BackupFile(new InstallFile(entry.Name, Package.InstallerInfo), PhysicalBasePath, Log); } Util.WriteStream(unzip, physicalPath); //Close files Element writer.WriteEndElement(); Log.AddInfo(string.Format(Util.FILE_Created, entry.Name)); } entry = unzip.GetNextEntry(); } //Close files Element writer.WriteEndElement(); Log.AddInfo(Util.FILES_CreatedResources); } catch (Exception exc) { Logger.Error(exc); retValue = false; } finally { if (writer != null) { //Close XmlWriter writer.Close(); } if (fs != null) { //Close FileStreams fs.Close(); } if (unzip != null) { unzip.Close(); } } return(retValue); }
private void BindGrid(string type, DataGrid grid, HtmlGenericControl noItemsControl) { var installPath = Globals.ApplicationMapPath + "\\Install\\" + type; var packages = new List <PackageInfo>(); var invalidPackages = new List <string>(); foreach (string file in Directory.GetFiles(installPath)) { if (file.ToLower().EndsWith(".zip") || file.ToLower().EndsWith(".resources")) { Stream inputStream = new FileStream(file, FileMode.Open, FileAccess.Read); var unzip = new ZipInputStream(inputStream); try { ZipEntry entry = unzip.GetNextEntry(); while (entry != null) { if (!entry.IsDirectory) { var fileName = entry.Name; string extension = Path.GetExtension(fileName); if (extension.ToLower() == ".dnn" || extension.ToLower() == ".dnn5") { //Manifest var manifestReader = new StreamReader(unzip); var manifest = manifestReader.ReadToEnd(); var package = new PackageInfo(); package.Manifest = manifest; if (!string.IsNullOrEmpty(manifest)) { var doc = new XPathDocument(new StringReader(manifest)); XPathNavigator rootNav = doc.CreateNavigator().SelectSingleNode("dotnetnuke"); string packageType = String.Empty; if (rootNav.Name == "dotnetnuke") { packageType = XmlUtils.GetAttributeValue(rootNav, "type"); } else if (rootNav.Name.ToLower() == "languagepack") { packageType = "LanguagePack"; } XPathNavigator nav = null; switch (packageType.ToLower()) { case "package": nav = rootNav.SelectSingleNode("packages/package"); break; case "languagepack": //nav = Installer.ConvertLegacyNavigator(rootNav, new InstallerInfo()).SelectSingleNode("packages/package"); break; } if (nav != null) { package.Name = XmlUtils.GetAttributeValue(nav, "name"); package.PackageType = XmlUtils.GetAttributeValue(nav, "type"); package.IsSystemPackage = XmlUtils.GetAttributeValueAsBoolean(nav, "isSystem", false); package.Version = new Version(XmlUtils.GetAttributeValue(nav, "version")); package.FriendlyName = XmlUtils.GetNodeValue(nav, "friendlyName"); if (String.IsNullOrEmpty(package.FriendlyName)) { package.FriendlyName = package.Name; } package.Description = XmlUtils.GetNodeValue(nav, "description"); package.FileName = file.Replace(installPath + "\\", ""); packages.Add(package); } } break; } } entry = unzip.GetNextEntry(); } } catch (Exception) { invalidPackages.Add(file); } finally { unzip.Close(); unzip.Dispose(); } } } if (invalidPackages.Count > 0) { var pkgErrorsMsg = invalidPackages.Aggregate(string.Empty, (current, pkg) => current + (pkg + "<br />")); Skin.AddModuleMessage(this, Localization.GetString("PackageErrors.Text", LocalResourceFile) + pkgErrorsMsg, ModuleMessage.ModuleMessageType.RedError); } if (packages.Count == 0) { noItemsControl.Visible = true; grid.Visible = false; } else { noItemsControl.Visible = false; grid.DataSource = packages; grid.DataBind(); } }
/// <summary> /// UnZip Theme /// </summary> /// <param name="themesPath"></param> /// <param name="fileStream"></param> public void UnZip(string themesPath, Stream fileStream) { ZipInputStream s = new ZipInputStream(fileStream); ZipEntry theEntry = null; while ((theEntry = s.GetNextEntry()) != null) { string directoryName = Path.GetDirectoryName(themesPath + theEntry.Name); string fileName = Path.GetFileName(theEntry.Name); // create directory if (directoryName.Length > 0) { Directory.CreateDirectory(directoryName); } if (fileName != String.Empty) { using (FileStream streamWriter = File.Create(themesPath + theEntry.Name)) { int size = 2048; byte[] data = new byte[2048]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } } } } s.Close(); }
public void EmptyZipEntries() { var ms = new MemoryStream(); var outStream = new ZipOutputStream(ms); for (var i = 0; i < 10; ++i) { outStream.PutNextEntry(new ZipEntry(i.ToString())); } outStream.Finish(); ms.Seek(0, SeekOrigin.Begin); var inStream = new ZipInputStream(ms); var extractCount = 0; ZipEntry entry; var decompressedData = new byte[100]; while ((entry = inStream.GetNextEntry()) != null) { while (true) { var numRead = inStream.Read(decompressedData, extractCount, decompressedData.Length); if (numRead <= 0) { break; } extractCount += numRead; } } inStream.Close(); Assert.AreEqual(extractCount, 0, "No data should be read from empty entries"); }
public void SkipEncryptedEntriesWithoutSettingPassword() { var compressedData = MakeInMemoryZip(true, new RuntimeInfo("1234", true), new RuntimeInfo(CompressionMethod.Deflated, 2, 1, null, true), new RuntimeInfo(CompressionMethod.Deflated, 9, 1, "1234", true), new RuntimeInfo(CompressionMethod.Deflated, 2, 1, null, true), new RuntimeInfo(null, true), new RuntimeInfo(CompressionMethod.Stored, 2, 1, "4321", true), new RuntimeInfo(CompressionMethod.Deflated, 9, 1, "1234", true) ); var ms = new MemoryStream(compressedData); var inStream = new ZipInputStream(ms); ZipEntry entry; while ((entry = inStream.GetNextEntry()) != null) { } inStream.Close(); }
/// <summary> /// 解压功能(解压压缩文件到指定目录) /// </summary> /// <param name="fileToUnZip">待解压的文件</param> /// <param name="zipedFolder">指定解压目标目录</param> /// <param name="password">密码</param> /// <returns>解压结果</returns> private bool UnZip(string fileToUnZip, string zipedFolder, string password) { bool result = true; FileStream fs = null; ZipInputStream zipStream = null; ZipEntry ent = null; string fileName; if (!File.Exists(fileToUnZip)) { return(false); } if (!Directory.Exists(zipedFolder)) { Directory.CreateDirectory(zipedFolder); } try { zipStream = new ZipInputStream(File.OpenRead(fileToUnZip)); if (!string.IsNullOrEmpty(password)) { zipStream.Password = password; } while ((ent = zipStream.GetNextEntry()) != null) { if (!string.IsNullOrEmpty(ent.Name)) { fileName = Path.Combine(zipedFolder, ent.Name); if (ent.IsDirectory) { Directory.CreateDirectory(fileName); continue; } fs = File.Create(fileName); int size = 2048; byte[] data = new byte[size]; while (true) { size = zipStream.Read(data, 0, data.Length); if (size > 0) { fs.Write(data, 0, data.Length); } else { break; } } } } } catch { result = false; } finally { if (fs != null) { fs.Close(); fs.Dispose(); } if (zipStream != null) { zipStream.Close(); zipStream.Dispose(); } if (ent != null) { ent = null; } GC.Collect(); GC.Collect(1); } return(result); }
/* * 압축파일을 받으면 압축을 풀어서 파일을 하나씩 원하는 경로에 저장하는 것 * zipFilePath: zip 파일의 경로 * upZipTargetFolderPath: 압축 해제 후 파일들 저장하려는 경로 * isDeleteZipFile: zip 파일의 삭제 여부(true 삭제, false 삭제안함) */ public bool UnZipFiles(string zipFilePath, string unZipTargetFolderPath, bool isDeleteZipFile) { bool retVal = false; // ZIP 파일이 있는 경우만 수행. if (File.Exists(zipFilePath)) { // 목록 생성을 위해 음악 카운트 더해줌 // 이걸로 파일이름을 지정해줌. //PlayerInformation.musicCount++; //loadMusicCount++; // Debug.Log("Exists Zip file"); // ZIP 스트림 생성. ZipInputStream zipInputStream = new ZipInputStream(File.OpenRead(zipFilePath)); try { // Debug.Log(zipInputStream.GetNextEntry()); ZipEntry theEntry; // 반복하며 파일을 가져옴. while ((theEntry = zipInputStream.GetNextEntry()) != null) { loadMusicCount++; if (loadMusicCount % 2 == 1) { PlayerInformation.musicCount++; } // 폴더 string directoryName = Path.GetDirectoryName(theEntry.Name); string fileName = Path.GetFileName(theEntry.Name); // 파일 string fileExtension = Path.GetExtension(theEntry.Name); // 파일 확장자만 // 폴더 생성 Directory.CreateDirectory(unZipTargetFolderPath + directoryName); Debug.Log(unZipTargetFolderPath + directoryName); // 파일 확장자 있는 경우 if (fileExtension != String.Empty) { // 파일 스트림 생성.(파일생성) FileStream streamWriter = File.Create((unZipTargetFolderPath + PlayerInformation.musicCount + fileExtension)); int size = 2048; byte[] data = new byte[size]; // 파일 복사 while (true) { size = zipInputStream.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } // 파일스트림 종료 streamWriter.Close(); } if (fileExtension.Equals(".txt")) { AddMusicInformation((PlayerInformation.musicCount).ToString()); AddListViewItem(); } } retVal = true; } catch { retVal = false; } finally { // ZIP 파일 스트림 종료 zipInputStream.Close(); } // ZIP파일 삭제를 원할 경우 파일 삭제. if (isDeleteZipFile) { try { File.Delete(zipFilePath); } catch {} } } return(retVal); }
/// <summary> /// 解压压缩文件到指定目录 /// </summary> /// <param name="zipFile">压缩文件</param> /// <param name="zipedDir">解压目录</param> /// <param name="zipedRelativePath">解压相对目录</param> /// <returns>解压的文件集的相对路径,多个用,分割</returns> public static string UnZip(string zipFile, string zipedDir, string zipedRelativePath) { //如果要解压的文件不存在 if (!File.Exists(zipFile)) { return(null); } //创建解压目录 if (!Directory.Exists(zipedDir)) { Directory.CreateDirectory(zipedDir); } StringBuilder imgsSB = new StringBuilder(); string imgsStr = null; ZipInputStream zipIS = null; ZipEntry zipEntry = null; FileStream streamWriter = null; try { string filePath; zipIS = new ZipInputStream(File.OpenRead(zipFile)); while ((zipEntry = zipIS.GetNextEntry()) != null) { if (zipEntry.Name != String.Empty) { filePath = Path.Combine(zipedDir, zipEntry.Name); //如果解压的是文件夹 if (filePath.EndsWith("/") || filePath.EndsWith("\\")) { Directory.CreateDirectory(filePath); continue; } streamWriter = File.Create(filePath); int size = 2048; byte[] data = new byte[2048]; while (true) { size = zipIS.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } imgsSB.Append(zipedRelativePath + "/" + zipEntry.Name + ";"); } } imgsStr = imgsSB.ToString(); imgsStr = imgsStr.Substring(0, imgsStr.Length - 1); } finally { //删除.zip文件 FileInfo f = new FileInfo(zipFile); if (f.Exists) { f.Delete(); } if (streamWriter != null) { streamWriter.Close(); streamWriter = null; } if (zipEntry != null) { zipEntry = null; } if (zipIS != null) { zipIS.Close(); zipIS = null; } GC.Collect(); GC.Collect(1); } return(imgsStr); }
/// <summary> /// 解压缩文件(压缩文件中含有子目录) /// </summary> /// <param name="zipfilepath">待解压缩的文件路径</param> /// <param name="unzippath">解压缩到指定目录</param> /// <returns>解压后的文件列表</returns> public List <string> UnZip(string zipfilepath, string unzippath) { //解压出来的文件列表 List <string> unzipFiles = new List <string>(); //检查输出目录是否以“\\”结尾 if (unzippath.EndsWith("\\") == false || unzippath.EndsWith(":\\") == false) { unzippath += "\\"; } ZipInputStream s = new ZipInputStream(File.OpenRead(zipfilepath)); ZipEntry theEntry; while ((theEntry = s.GetNextEntry()) != null) { string directoryName = Path.GetDirectoryName(unzippath); string fileName = Path.GetFileName(theEntry.Name); //生成解压目录【用户解压到硬盘根目录时,不需要创建】 if (!string.IsNullOrEmpty(directoryName)) { Directory.CreateDirectory(directoryName); } if (fileName != String.Empty) { //如果文件的压缩后大小为0那么说明这个文件是空的,因此不需要进行读出写入 if (theEntry.CompressedSize == 0) { break; } //解压文件到指定的目录 directoryName = Path.GetDirectoryName(unzippath + theEntry.Name); //建立下面的目录和子目录 Directory.CreateDirectory(directoryName); //记录导出的文件 unzipFiles.Add(unzippath + theEntry.Name); FileStream streamWriter = File.Create(unzippath + theEntry.Name); int size = 2048; byte[] data = new byte[2048]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } streamWriter.Close(); } } s.Close(); GC.Collect(); return(unzipFiles); }
public bool DecompressFiles(String zipPath, String destination) { bool result = false; try { using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipPath))) { ZipEntry entry; String tmpEntry = String.Empty; while ((entry = s.GetNextEntry()) != null) { string dirName = destination; string fileName = Path.GetFileName(entry.Name); if (dirName != "") { Directory.CreateDirectory(dirName); } if (fileName != string.Empty) { if (entry.Name.IndexOf(".ini") < 0) { String FileName = dirName + "\\" + entry.Name; FileName = FileName.Replace("\\ ", "\\"); String FolderName = Path.GetDirectoryName(FileName); if (Directory.Exists(FolderName) == false) { Directory.CreateDirectory(FolderName); } FileStream fStream = File.Create(FileName); int StreamSize = 2048; byte[] buffer = new byte[2048]; while (true) { StreamSize = s.Read(buffer, 0, buffer.Length); if (StreamSize > 0) { fStream.Write(buffer, 0, StreamSize); } else { break; } } fStream.Close(); } } } s.Close(); } if (Directory.Exists(destination)) { result = true; } } catch (Exception ex) { MessageBox.Show("Failed to unzip the file.\n" + ex.Message, "DecompressFiles", MessageBoxButton.OK, MessageBoxImage.Warning); result = false; } return(result); }
public void UnZip(string zipedFile, string strDirectory, string password, bool overWrite) { ZipInputStream zipInputStream = null; try { if (strDirectory == "") { strDirectory = Directory.GetCurrentDirectory(); } if (!strDirectory.EndsWith("\\")) { strDirectory += "\\"; } using (zipInputStream = new ZipInputStream(File.OpenRead(zipedFile))) { zipInputStream.Password = password; ZipEntry nextEntry; while ((nextEntry = zipInputStream.GetNextEntry()) != null) { nextEntry.IsUnicodeText = true; string str = ""; string text = ""; text = nextEntry.Name; if (text.Contains("?")) { text = text.Replace('?', '_'); } if (text != "") { str = Path.GetDirectoryName(text) + "\\"; } string fileName = Path.GetFileName(text); Directory.CreateDirectory(strDirectory + str); if (fileName != "") { try { if ((File.Exists(strDirectory + str + fileName) && overWrite) || !File.Exists(strDirectory + str + fileName)) { using (FileStream fileStream = File.Create(strDirectory + str + fileName)) { int num = 2048; byte[] array = new byte[2048]; try { while (true) { num = zipInputStream.Read(array, 0, array.Length); if (num <= 0) { break; } fileStream.Write(array, 0, num); } fileStream.Close(); } catch (Exception) { fileStream.Close(); } } } } catch (Exception) { } } } zipInputStream.Close(); } } catch (Exception) { try { zipInputStream.Close(); } catch { } } }
private void BindGrid(string installPath, DataGrid grid) { var packages = new List <PackageInfo>(); var invalidPackages = new List <string>(); foreach (string file in Directory.GetFiles(installPath)) { if (file.ToLower().EndsWith(".zip") || file.ToLower().EndsWith(".resources")) { Stream inputStream = new FileStream(file, FileMode.Open, FileAccess.Read); var unzip = new ZipInputStream(inputStream); try { ZipEntry entry = unzip.GetNextEntry(); while (entry != null) { if (!entry.IsDirectory) { string fileName = entry.Name; string extension = Path.GetExtension(fileName); if (extension.ToLower() == ".dnn" || extension.ToLower() == ".dnn5") { //Manifest var manifestReader = new StreamReader(unzip); string manifest = manifestReader.ReadToEnd(); var package = new PackageInfo(); package.Manifest = manifest; if (!string.IsNullOrEmpty(manifest)) { var doc = new XPathDocument(new StringReader(manifest)); XPathNavigator rootNav = doc.CreateNavigator().SelectSingleNode("dotnetnuke"); string packageType = String.Empty; if (rootNav.Name == "dotnetnuke") { packageType = XmlUtils.GetAttributeValue(rootNav, "type"); } else if (rootNav.Name.ToLower() == "languagepack") { packageType = "LanguagePack"; } XPathNavigator nav = null; switch (packageType.ToLower()) { case "package": nav = rootNav.SelectSingleNode("packages/package"); break; case "languagepack": nav = Installer.ConvertLegacyNavigator(rootNav, new InstallerInfo()).SelectSingleNode("packages/package"); break; } if (nav != null) { package.Name = XmlUtils.GetAttributeValue(nav, "name"); package.PackageType = XmlUtils.GetAttributeValue(nav, "type"); package.IsSystemPackage = XmlUtils.GetAttributeValueAsBoolean(nav, "isSystem", false); package.Version = new Version(XmlUtils.GetAttributeValue(nav, "version")); package.FriendlyName = XmlUtils.GetNodeValue(nav, "friendlyName"); if (String.IsNullOrEmpty(package.FriendlyName)) { package.FriendlyName = package.Name; } package.Description = XmlUtils.GetNodeValue(nav, "description"); package.FileName = file.Replace(installPath + "\\", ""); packages.Add(package); } } break; } } entry = unzip.GetNextEntry(); } } catch (Exception) { invalidPackages.Add(file); } finally { unzip.Close(); unzip.Dispose(); } } } //now add language packs from update service try { StreamReader myResponseReader = UpdateService.GetLanguageList(); var xmlDoc = new XmlDocument(); xmlDoc.Load(myResponseReader); XmlNodeList languages = xmlDoc.SelectNodes("available/language"); if (languages != null) { var installedPackages = PackageController.Instance.GetExtensionPackages(Null.NullInteger, p => p.PackageType == "CoreLanguagePack"); var installedLanguages = installedPackages.Select(package => LanguagePackController.GetLanguagePackByPackage(package.PackageID)).ToList(); foreach (XmlNode language in languages) { string cultureCode = ""; string version = ""; foreach (XmlNode child in language.ChildNodes) { if (child.Name == "culturecode") { cultureCode = child.InnerText; } if (child.Name == "version") { version = child.InnerText; } } if (!string.IsNullOrEmpty(cultureCode) && !string.IsNullOrEmpty(version) && version.Length == 6) { var myCIintl = new CultureInfo(cultureCode, true); version = version.Insert(4, ".").Insert(2, "."); var package = new PackageInfo { Owner = OwnerUpdateService, Name = "LanguagePack-" + myCIintl.Name, FriendlyName = myCIintl.NativeName }; package.Name = myCIintl.NativeName; package.Description = cultureCode; Version ver = null; Version.TryParse(version, out ver); package.Version = ver; if ( installedLanguages.Any( l => LocaleController.Instance.GetLocale(l.LanguageID).Code.ToLowerInvariant().Equals(cultureCode.ToLowerInvariant()) && installedPackages.First(p => p.PackageID == l.PackageID).Version >= ver)) { continue; } if (packages.Any(p => p.Name == package.Name)) { var existPackage = packages.First(p => p.Name == package.Name); if (package.Version > existPackage.Version) { packages.Remove(existPackage); packages.Add(package); } } else { packages.Add(package); } } } } } catch (Exception) { //suppress for now - need to decide what to do when webservice is unreachable //throw; //same problem happens in InstallWizard.aspx.cs in BindLanguageList method } if (invalidPackages.Count > 0) { string pkgErrorsMsg = invalidPackages.Aggregate(string.Empty, (current, pkg) => current + (pkg + "<br />")); Skin.AddModuleMessage(this, Localization.GetString("PackageErrors.Text", LocalResourceFile) + pkgErrorsMsg, ModuleMessage.ModuleMessageType.RedError); } grid.DataSource = packages; grid.DataBind(); }
private void unzip(string path, string foldername, string rootFolder) { ZipInputStream s = new ZipInputStream(File.OpenRead(path)); ZipEntry theEntry; var stopDir = "\\Documentation"; string serverFolder = rootFolder + "\\" + foldername; List <string> existingFiles = new List <string>(); if (Directory.Exists(serverFolder)) { var files = string.Join("|", Directory.GetFiles(serverFolder, "*.md", SearchOption.AllDirectories)).ToLower().Split('|'); existingFiles.AddRange(files); } else { Directory.CreateDirectory(serverFolder); } try { bool stopDirSet = false; while ((theEntry = s.GetNextEntry()) != null) { if (IsProjectDocumentation && !stopDirSet) { stopDir = Path.GetDirectoryName(theEntry.Name); stopDirSet = true; } string directoryName = Path.GetDirectoryName(theEntry.Name); string fileName = Path.GetFileName(theEntry.Name); HttpContext.Current.Trace.Write("git", theEntry.Name + " " + fileName + " - " + directoryName); if (directoryName.Contains(stopDir)) { var startIndex = directoryName.LastIndexOf(stopDir) + stopDir.Length; directoryName = directoryName.Substring(startIndex); // create directory Directory.CreateDirectory(serverFolder + directoryName); if (fileName != String.Empty) { bool update = false; var filepath = serverFolder + directoryName + "\\" + fileName; if (existingFiles.Contains(filepath.ToLower())) { update = true; existingFiles.Remove(filepath.ToLower()); } FileStream streamWriter = File.Create(filepath); int size = 2048; byte[] data = new byte[2048]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } streamWriter.Close(); if (update) { UpdateEventArgs ev = new UpdateEventArgs(); ev.FilePath = filepath; FireOnUpdate(ev); } else { CreateEventArgs ev = new CreateEventArgs(); ev.FilePath = filepath; FireOnCreate(ev); } } } } s.Close(); foreach (var file in Directory.GetFiles(rootFolder, "*.zip")) { File.Delete(file); } foreach (var file in existingFiles) { DeleteEventArgs ev = new DeleteEventArgs(); ev.FilePath = file; FireOnDelete(ev); } } catch (Exception ex) { Log.Add(LogTypes.Error, -1, ex.ToString()); } }
private void StartUnZipFileByStream() { if (mStream == null) { Error = "Stream = null"; IsDone = true; return; } try { using (ZipInputStream f = new ZipInputStream(mStream)) { long tunziplen = 0; long tFileLen = mStream.Length; string un_dir = mDestinationFilePath; ZipEntry zp = f.GetNextEntry(); int tcachelen = 2048; byte[] tcachebuffer = new byte[tcachelen]; //每次缓冲 2048 字节 while (zp != null && mThreadRuning) { CurFile = zp.Name; tunziplen += zp.CompressedSize; progress = (float)tunziplen / tFileLen; string un_tmp2; if (zp.Name.IndexOf("/") >= 0) { int tmp1 = zp.Name.LastIndexOf("/"); un_tmp2 = zp.Name.Substring(0, tmp1); if (!Directory.Exists(un_dir + un_tmp2)) { Directory.CreateDirectory(un_dir + un_tmp2); } } if (!zp.IsDirectory && zp.Crc != 00000000L) //此“ZipEntry”不是“标记文件” { string tnewfile = un_dir + "/" + zp.Name; if (File.Exists(tnewfile)) { File.Delete(tnewfile); } using (FileStream ts = File.Create(tnewfile)) { int treadlen = 0; while (true && mThreadRuning) //持续读取字节,直到一个“ZipEntry”字节读完 { treadlen = f.Read(tcachebuffer, 0, tcachebuffer.Length); //读取“ZipEntry”中的字节 if (treadlen > 0) { ts.Write(tcachebuffer, 0, treadlen); //将字节写入新建的文件流 } else { break; //读取的字节为 0 ,跳出循环 } } ts.Flush(); ts.Close(); } } zp = f.GetNextEntry(); } f.Close(); } } catch (System.Exception _error) { Error = _error.ToString(); } progress = 1; mStream.Close(); mStream.Dispose(); mStream = null; IsDone = true; }
/// <summary> /// 解压功能(解压压缩文件到指定目录) /// </summary> /// <param name="fileToUnZip">待解压的文件</param> /// <param name="zipedFolder">指定解压目标目录</param> /// <param name="password">密码</param> /// <returns>解压结果</returns> public static bool UnZip(string fileToUnZip, string zipedFolder, string password) { bool result = true; FileStream fs = null; ZipInputStream zipStream = null; ZipEntry ent = null; string fileName; if (!File.Exists(fileToUnZip)) { return(false); } if (!Directory.Exists(zipedFolder)) { Directory.CreateDirectory(zipedFolder); } try { zipStream = new ZipInputStream(File.OpenRead(fileToUnZip)); if (!string.IsNullOrEmpty(password)) { zipStream.Password = password; } while ((ent = zipStream.GetNextEntry()) != null) { if (!string.IsNullOrEmpty(ent.Name)) { fileName = Path.Combine(zipedFolder, ent.Name); fileName = fileName.Replace('/', '\\');//change by Mr.HopeGi if (fileName.EndsWith("\\")) { Directory.CreateDirectory(fileName); continue; } string dir = fileName.Substring(0, fileName.LastIndexOf("\\")); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } fs = File.Create(fileName); int size = 2048; byte[] data = new byte[size]; while (true) { size = zipStream.Read(data, 0, data.Length); if (size > 0) { fs.Write(data, 0, size); } else { break; } } } } } catch { result = false; } finally { if (fs != null) { fs.Close(); fs.Dispose(); } if (zipStream != null) { zipStream.Close(); zipStream.Dispose(); } if (ent != null) { ent = null; } GC.Collect(); GC.Collect(1); } return(result); }
private void unzipEPubAndParseOpf() { ZipInputStream zipInputStream = new ZipInputStream(File.OpenRead(m_Book_FilePath)); /*string directoryName = Path.GetTempPath(); * if (!directoryName.EndsWith("" + Path.DirectorySeparatorChar)) * { * directoryName += Path.DirectorySeparatorChar; * }*/ string unzipDirectory = Path.Combine(m_outDirectory, m_Book_FilePath.Replace(".", "_")); if (Directory.Exists(unzipDirectory)) { Directory.Delete(unzipDirectory, true); } ZipEntry zipEntry; while ((zipEntry = zipInputStream.GetNextEntry()) != null) { string zipEntryName = Path.GetFileName(zipEntry.Name); if (!String.IsNullOrEmpty(zipEntryName)) // || zipEntryName.IndexOf(".ini") >= 0 { // string unzippedFilePath = Path.Combine(unzipDirectory, zipEntryName); string unzippedFilePath = unzipDirectory + Path.DirectorySeparatorChar + zipEntry.Name; string unzippedFileDir = Path.GetDirectoryName(unzippedFilePath); if (!Directory.Exists(unzippedFileDir)) { Directory.CreateDirectory(unzippedFileDir); } FileStream fileStream = File.Create(unzippedFilePath); byte[] data = new byte[2 * 1024]; // 2 KB buffer int bytesRead = 0; try { while ((bytesRead = zipInputStream.Read(data, 0, data.Length)) > 0) { fileStream.Write(data, 0, bytesRead); } } finally { fileStream.Close(); } } } zipInputStream.Close(); var dirInfo = new DirectoryInfo(unzipDirectory); FileInfo[] opfFiles = dirInfo.GetFiles("*.opf ", SearchOption.AllDirectories); foreach (FileInfo fileInfo in opfFiles) { m_Book_FilePath = Path.Combine(unzipDirectory, fileInfo.FullName); XmlDocument opfXmlDoc = readXmlDocument(m_Book_FilePath); parseOpf(opfXmlDoc); break; } }
internal ZipPackage(Stream stream) { bool hasContentTypeXml = false; if (stream == null || stream.Length == 0) { AddNew(); } else { var rels = new Dictionary <string, string>(); stream.Seek(0, SeekOrigin.Begin); using (ZipInputStream zip = new ZipInputStream(stream)) { var e = zip.GetNextEntry(); if (e.FileName.Contains("\\")) { _dirSeparator = '\\'; } else { _dirSeparator = '/'; } while (e != null) { if (e.UncompressedSize > 0) { var b = new byte[e.UncompressedSize]; var size = zip.Read(b, 0, (int)e.UncompressedSize); if (e.FileName.Equals("[content_types].xml", StringComparison.OrdinalIgnoreCase)) { AddContentTypes(Encoding.UTF8.GetString(b)); hasContentTypeXml = true; } else if (e.FileName.Equals($"_rels{_dirSeparator}.rels", StringComparison.OrdinalIgnoreCase)) { ReadRelation(Encoding.UTF8.GetString(b), ""); } else { if (e.FileName.EndsWith(".rels", StringComparison.OrdinalIgnoreCase)) { rels.Add(GetUriKey(e.FileName), Encoding.UTF8.GetString(b)); } else { var part = new ZipPackagePart(this, e); part.Stream = new MemoryStream(); part.Stream.Write(b, 0, b.Length); Parts.Add(GetUriKey(e.FileName), part); } } } else { } e = zip.GetNextEntry(); } foreach (var p in Parts) { string name = Path.GetFileName(p.Key); string extension = Path.GetExtension(p.Key); string relFile = string.Format("{0}_rels/{1}.rels", p.Key.Substring(0, p.Key.Length - name.Length), name); if (rels.ContainsKey(relFile)) { p.Value.ReadRelation(rels[relFile], p.Value.Uri.OriginalString); } if (_contentTypes.ContainsKey(p.Key)) { p.Value.ContentType = _contentTypes[p.Key].Name; } else if (extension.Length > 1 && _contentTypes.ContainsKey(extension.Substring(1))) { p.Value.ContentType = _contentTypes[extension.Substring(1)].Name; } } if (!hasContentTypeXml) { throw (new InvalidDataException("The file is not an valid Package file. If the file is encrypted, please supply the password in the constructor.")); } if (!hasContentTypeXml) { throw (new InvalidDataException("The file is not an valid Package file. If the file is encrypted, please supply the password in the constructor.")); } zip.Close(); zip.Dispose(); } } }
/// <summary> /// 解压文件 /// </summary> /// <param name="TargetFile">待解压的文件 (包括全路径.zip)</param> /// <param name="fileDir">解压后放置的目标目录 路径</param> /// <returns></returns> public string unZipFile(string TargetFile, string fileDir) { string rootFile = " "; try { //读取压缩文件(zip文件),准备解压缩 ZipInputStream s = new ZipInputStream(File.OpenRead(TargetFile.Trim())); ZipEntry theEntry; string path = fileDir; //解压出来的文件保存的路径 string rootDir = " "; //根目录下的第一个子文件夹的名称 while ((theEntry = s.GetNextEntry()) != null) { rootDir = Path.GetDirectoryName(theEntry.Name); //得到根目录下的第一级子文件夹的名称 if (rootDir.IndexOf("\\") >= 0) { rootDir = rootDir.Substring(0, rootDir.IndexOf("\\") + 1); } string dir = Path.GetDirectoryName(theEntry.Name); //根目录下的第一级子文件夹的下的文件夹的名称 string fileName = Path.GetFileName(theEntry.Name); //根目录下的文件名称 if (dir != " ") //创建根目录下的子文件夹,不限制级别 { if (!Directory.Exists(fileDir + "\\" + dir)) { path = fileDir + "\\" + dir; //在指定的路径创建文件夹 Directory.CreateDirectory(path); } } else if (dir == " " && fileName != "") //根目录下的文件 { path = fileDir; rootFile = fileName; } else if (dir != " " && fileName != "") //根目录下的第一级子文件夹下的文件 { if (dir.IndexOf("\\") > 0) //指定文件保存的路径 { path = fileDir + "\\" + dir; } } if (dir == rootDir) //判断是不是需要保存在根目录下的文件 { path = fileDir + "\\" + rootDir; } //以下为解压缩zip文件的基本步骤 //基本思路就是遍历压缩文件里的所有文件,创建一个相同的文件。 if (fileName != String.Empty) { FileStream streamWriter = File.Create(path + "\\" + fileName); int size = 2048; byte[] data = new byte[2048]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } streamWriter.Close(); } } s.Close(); return(rootFile); } catch (Exception ex) { return("1; " + ex.Message); } }
public static string UploadLegacySkin(string rootPath, string skinRoot, string skinName, Stream inputStream) { var objZipInputStream = new ZipInputStream(inputStream); ZipEntry objZipEntry; string strExtension; string strFileName; FileStream objFileStream; int intSize = 2048; var arrData = new byte[2048]; string strMessage = ""; var arrSkinFiles = new ArrayList(); //Localized Strings PortalSettings ResourcePortalSettings = Globals.GetPortalSettings(); string BEGIN_MESSAGE = Localization.GetString("BeginZip", ResourcePortalSettings); string CREATE_DIR = Localization.GetString("CreateDir", ResourcePortalSettings); string WRITE_FILE = Localization.GetString("WriteFile", ResourcePortalSettings); string FILE_ERROR = Localization.GetString("FileError", ResourcePortalSettings); string END_MESSAGE = Localization.GetString("EndZip", ResourcePortalSettings); string FILE_RESTICTED = Localization.GetString("FileRestricted", ResourcePortalSettings); strMessage += FormatMessage(BEGIN_MESSAGE, skinName, -1, false); objZipEntry = objZipInputStream.GetNextEntry(); while (objZipEntry != null) { if (!objZipEntry.IsDirectory) { //validate file extension strExtension = objZipEntry.Name.Substring(objZipEntry.Name.LastIndexOf(".") + 1); var extraExtensions = new List <string> { ".ASCX", ".HTM", ".HTML", ".CSS", ".SWF", ".RESX", ".XAML", ".JS" }; if (Host.AllowedExtensionWhitelist.IsAllowedExtension(strExtension, extraExtensions)) { //process embedded zip files if (objZipEntry.Name.Equals(RootSkin.ToLowerInvariant() + ".zip", StringComparison.InvariantCultureIgnoreCase)) { using (var objMemoryStream = new MemoryStream()) { intSize = objZipInputStream.Read(arrData, 0, arrData.Length); while (intSize > 0) { objMemoryStream.Write(arrData, 0, intSize); intSize = objZipInputStream.Read(arrData, 0, arrData.Length); } objMemoryStream.Seek(0, SeekOrigin.Begin); strMessage += UploadLegacySkin(rootPath, RootSkin, skinName, objMemoryStream); } } else if (objZipEntry.Name.Equals(RootContainer.ToLowerInvariant() + ".zip", StringComparison.InvariantCultureIgnoreCase)) { using (var objMemoryStream = new MemoryStream()) { intSize = objZipInputStream.Read(arrData, 0, arrData.Length); while (intSize > 0) { objMemoryStream.Write(arrData, 0, intSize); intSize = objZipInputStream.Read(arrData, 0, arrData.Length); } objMemoryStream.Seek(0, SeekOrigin.Begin); strMessage += UploadLegacySkin(rootPath, RootContainer, skinName, objMemoryStream); } } else { strFileName = rootPath + skinRoot + "\\" + skinName + "\\" + objZipEntry.Name; //create the directory if it does not exist if (!Directory.Exists(Path.GetDirectoryName(strFileName))) { strMessage += FormatMessage(CREATE_DIR, Path.GetDirectoryName(strFileName), 2, false); Directory.CreateDirectory(Path.GetDirectoryName(strFileName)); } //remove the old file if (File.Exists(strFileName)) { File.SetAttributes(strFileName, FileAttributes.Normal); File.Delete(strFileName); } //create the new file objFileStream = File.Create(strFileName); //unzip the file strMessage += FormatMessage(WRITE_FILE, Path.GetFileName(strFileName), 2, false); intSize = objZipInputStream.Read(arrData, 0, arrData.Length); while (intSize > 0) { objFileStream.Write(arrData, 0, intSize); intSize = objZipInputStream.Read(arrData, 0, arrData.Length); } objFileStream.Close(); //save the skin file switch (Path.GetExtension(strFileName)) { case ".htm": case ".html": case ".ascx": case ".css": if (strFileName.ToLowerInvariant().IndexOf(Globals.glbAboutPage.ToLowerInvariant()) < 0) { arrSkinFiles.Add(strFileName); } break; } break; } } else { strMessage += string.Format(FILE_RESTICTED, objZipEntry.Name, Host.AllowedExtensionWhitelist.ToStorageString(), ",", ", *.").Replace("2", "true"); } } objZipEntry = objZipInputStream.GetNextEntry(); } strMessage += FormatMessage(END_MESSAGE, skinName + ".zip", 1, false); objZipInputStream.Close(); //process the list of skin files var NewSkin = new SkinFileProcessor(rootPath, skinRoot, skinName); strMessage += NewSkin.ProcessList(arrSkinFiles, SkinParser.Portable); //log installation event try { var log = new LogInfo { LogTypeKey = EventLogController.EventLogType.HOST_ALERT.ToString() }; log.LogProperties.Add(new LogDetailInfo("Install Skin:", skinName)); Array arrMessage = strMessage.Split(new[] { "<br />" }, StringSplitOptions.None); foreach (string strRow in arrMessage) { log.LogProperties.Add(new LogDetailInfo("Info:", HtmlUtils.StripTags(strRow, true))); } LogController.Instance.AddLog(log); } catch (Exception exc) { Logger.Error(exc); } return(strMessage); }
public static void UnZip(string FileToUpZip, string ZipedFolder, string Password) { if (!File.Exists(FileToUpZip)) { return; } if (!Directory.Exists(ZipedFolder)) { Directory.CreateDirectory(ZipedFolder); } ZipInputStream s = null; ZipEntry theEntry = null; string fileName; FileStream streamWriter = null; try { s = new ZipInputStream(File.OpenRead(FileToUpZip)); s.Password = Password; while ((theEntry = s.GetNextEntry()) != null) { if (theEntry.Name != String.Empty) { fileName = Path.Combine(ZipedFolder, theEntry.Name); if (fileName.EndsWith("/") || fileName.EndsWith("\\")) { Directory.CreateDirectory(fileName); continue; } streamWriter = File.Create(fileName); int size = 2048; byte[] data = new byte[2048]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } } } } finally { if (streamWriter != null) { streamWriter.Close(); streamWriter = null; } if (theEntry != null) { theEntry = null; } if (s != null) { s.Close(); s = null; } GC.Collect(); GC.Collect(1); } }
public static void UnZipFiles(string zipPathAndFile, string outputFolder, string password, bool deleteZipFile) { ZipInputStream zipInputStream = null; FileStream fileStream = null; try { zipInputStream = new ZipInputStream(File.OpenRead(zipPathAndFile)); if (!string.IsNullOrEmpty(password)) { zipInputStream.Password = password; } string empty = string.Empty; ZipEntry nextEntry; while ((nextEntry = zipInputStream.GetNextEntry()) != null) { string fileName = Path.GetFileName(nextEntry.Name); if (!string.IsNullOrEmpty(outputFolder) && !Directory.Exists(outputFolder)) { Directory.CreateDirectory(outputFolder); } if (fileName != string.Empty && nextEntry.Name.IndexOf(".ini") < 0) { string text = outputFolder + "\\" + nextEntry.Name; text = text.Replace("\\ ", "\\"); string directoryName = Path.GetDirectoryName(text); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } fileStream = File.Create(text); byte[] array = new byte[2048]; for (;;) { int num = zipInputStream.Read(array, 0, array.Length); if (num <= 0) { break; } fileStream.Write(array, 0, num); } fileStream.Close(); } } zipInputStream.Close(); } catch (Exception value) { Console.WriteLine(value); } finally { if (zipInputStream != null) { zipInputStream.Dispose(); } if (fileStream != null) { fileStream.Dispose(); } } if (deleteZipFile) { try { File.Delete(zipPathAndFile); } catch { } } }
/// <summary> /// 解压文件操作 /// </summary> /// <param name="softwareContent">要解压的二进制</param> /// <param name="zipedFolder">解压后的文件路径</param> /// <param name="password">密码</param> /// <returns></returns> private static bool UnZipFileOperation(byte[] softwareContent, string zipedFolder, string password) { /* 防止中文路径乱码TODO */ //ZipConstants.DefaultCodePage = "GBK"; bool result = true; FileStream fs = null; ZipInputStream zipStream = null; ZipEntry ent = null; string fileName; if (!Directory.Exists(zipedFolder)) { Directory.CreateDirectory(zipedFolder); } try { Stream stream = new MemoryStream(softwareContent); zipStream = new ZipInputStream(stream); if (!string.IsNullOrEmpty(password)) { zipStream.Password = password; } while ((ent = zipStream.GetNextEntry()) != null) { if (!string.IsNullOrEmpty(ent.Name)) { fileName = Path.Combine(zipedFolder, ent.Name); fileName = fileName.Replace('/', '\\'); if (fileName.EndsWith("\\")) { Directory.CreateDirectory(fileName); continue; } fs = System.IO.File.Create(fileName); #region 一次性读取 //int size = 2048; //byte[] data = new byte[size];// 这么写如果文件不足2048 文件输出后面会有空白 int size; byte[] data = new byte[zipStream.Length]; while (true) { size = zipStream.Read(data, 0, data.Length); if (size > 0) { fs.Write(data, 0, data.Length); } else { break; } } #endregion #region 分段读取 /* 每次读取的长度 */ //int maxLength = 1024; ///* 分段读取 */ //byte[] data = new byte[maxLength]; ////读取位置 //int start = 0; ////实际返回结果长度 //int num = 0; ////尚未读取的文件内容长度 //long left = zipStream.Length; //while (left > 0) //{ // fs.Position = start; // num = 0; // if (left < maxLength) // { // num = zipStream.Read(data, 0, Convert.ToInt32(left)); // } // else // { // num = zipStream.Read(data, 0, maxLength); // } // if (num == 0) // { // break; // } // else // { // fs.Write(data, 0, num); // } // start += num; // left -= num; //} #endregion fs.Close(); } } } catch (Exception e) { result = false; } finally { if (fs != null) { fs.Close(); fs.Dispose(); } if (zipStream != null) { zipStream.Close(); zipStream.Dispose(); } if (ent != null) { ent = null; } //GC.Collect(); //GC.Collect(1); } return(result); }
/// <summary> /// ZIP:解压一个zip文件 /// add yuangang by 2016-06-13 /// </summary> /// <param name="ZipFile">需要解压的Zip文件(绝对路径)</param> /// <param name="TargetDirectory">解压到的目录</param> /// <param name="Password">解压密码</param> /// <param name="OverWrite">是否覆盖已存在的文件</param> public static void UnZip(string ZipFile, string TargetDirectory, string Password = "", bool OverWrite = true) { //如果解压到的目录不存在,则报错 if (!Directory.Exists(TargetDirectory)) { try { Directory.CreateDirectory(TargetDirectory); } catch (Exception ex) { LogUtil.WriteLog(ex); throw new FileNotFoundException("指定的目录: " + TargetDirectory + $" 不存在!{ex.Message}"); } } //目录结尾 if (!TargetDirectory.EndsWith("\\")) { TargetDirectory = TargetDirectory + "\\"; } using (ZipInputStream zipfiles = new ZipInputStream(File.OpenRead(ZipFile))) { if (!string.IsNullOrEmpty(Password)) { zipfiles.Password = Password; } ZipEntry theEntry; while ((theEntry = zipfiles.GetNextEntry()) != null) { string directoryName = ""; string pathToZip = ""; pathToZip = theEntry.Name; if (pathToZip != "") { directoryName = Path.GetDirectoryName(pathToZip) + "\\"; } string fileName = Path.GetFileName(pathToZip); Directory.CreateDirectory(TargetDirectory + directoryName); if (fileName != "") { if ((File.Exists(TargetDirectory + directoryName + fileName) && OverWrite) || (!File.Exists(TargetDirectory + directoryName + fileName))) { using (FileStream streamWriter = File.Create(TargetDirectory + directoryName + fileName)) { int size = 2048; byte[] data = new byte[2048]; while (true) { size = zipfiles.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } streamWriter.Close(); } } } } zipfiles.Close(); } }
/// <summary> /// 解压文件 /// </summary> /// <param name="TargetFile">待解压的文件</param> /// <param name="fileDir">解压后存放路径</param> /// <returns></returns> public static bool unZipFile(string TargetFile, string fileDir) { try { /* 读取压缩文件(zip文件),准备解压缩 */ ZipInputStream s = new ZipInputStream(File.OpenRead(TargetFile.Trim())); ZipEntry theEntry; /* 解压出来的文件保存的路径 */ string path = fileDir; /* 根目录下的第一级子文件夹的名称 */ string rootDir = " "; while ((theEntry = s.GetNextEntry()) != null) { /* 得到根目录下的第一级子文件夹的名称 */ rootDir = Path.GetDirectoryName(theEntry.Name); if (rootDir.IndexOf("\\") >= 0) { rootDir = rootDir.Substring(0, rootDir.IndexOf("\\") + 1); } /* 根目录下的第一级子文件夹的下的文件夹的名称 */ string dir = Path.GetDirectoryName(theEntry.Name); /* 根目录下的文件名称 */ string fileName = Path.GetFileName(theEntry.Name); /* 创建根目录下的子文件夹,不限制级别 */ if (dir != " ") { if (!Directory.Exists(fileDir + "\\" + dir)) { //在指定的路径创建文件夹 path = fileDir + "\\" + dir; Directory.CreateDirectory(path); } } /* 根目录下的文件 */ else if (dir == " " && fileName != "") { path = fileDir; } else if (dir != " " && fileName != "") /* 根目录下的第一级子文件夹下的文件 */ { /* 指定文件保存的路径 */ if (dir.IndexOf("\\") > 0) { path = fileDir + "\\" + dir; } } /* 判断是不是需要保存在根目录下的文件 */ if (dir == rootDir) { path = fileDir + "\\" + rootDir; } if (fileName != String.Empty) { FileStream streamWriter = File.Create(path + "\\" + fileName); int size = 2048; byte[] data = new byte[2048]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } streamWriter.Close(); } } s.Close(); return(true); } catch (Exception ex) { return(false); } }
private void analyzeFile(string filePath, string fileName) { //解压文件 ZipInputStream s = new ZipInputStream(File.OpenRead(filePath + "\\" + fileName)); ZipEntry theEntry; while ((theEntry = s.GetNextEntry()) != null) { string directoryName = Path.GetDirectoryName(filePath); fileName = Path.GetFileName(theEntry.Name); //生成解压目录 Directory.CreateDirectory(directoryName); if (fileName != String.Empty) { //解压文件到指定的目录 FileStream streamWriter = File.Create(filePath + theEntry.Name); int size = 2048; byte[] data = new byte[2048]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } streamWriter.Close(); } } s.Close(); //遍历解压之后目录下的所有文件,对流水文件分析 foreach (string file in Directory.GetFiles(filePath)) { fileName = file.Substring(filePath.Length); List <Dictionary <int, string> > list = null; if (fileName.Substring(0, 3) == "INN" && fileName.Substring(11, 3) == "ZM_") { list = parseZMFile(file); } else if (fileName.Substring(0, 3) == "INN" && fileName.Substring(11, 4) == "ZME_") { list = parseZMEFile(file); } if (list != null) { Response.Write(fileName + "部分参数读取(读取方式请参考Form_7_2_FileTransfer的代码):<br>\n"); Response.Write("<table border='1'>\n"); Response.Write("<tr><th>txnType</th><th>orderId</th><th>txnTime(MMDDhhmmss)</th></tr>"); foreach (Dictionary <int, string> dic in list) { //TODO 参看https://open.unionpay.com/ajweb/help?id=258,根据编号获取即可,例如订单号12、交易类型20。 //具体写代码时可能边读文件边修改数据库性能会更好,请注意自行根据parseFile中的读取方法修改。 Response.Write("<tr>\n"); Response.Write("<td>" + dic[20] + "</td>\n"); //txnType Response.Write("<td>" + dic[12] + "</td>\n"); //orderId Response.Write("<td>" + dic[5] + "</td>\n"); //txnTime不带年份 Response.Write("</tr>\n"); } Response.Write("</table>\n"); } } }
private ISerializable UnZipZeroLength(byte[] zipped) { if (zipped == null) { return null; } object result = null; var formatter = new XmlFormatter(); var memStream = new MemoryStream(zipped); using (var zipStream = new ZipInputStream(memStream)) { var zipEntry = zipStream.GetNextEntry(); if (zipEntry != null) { result = formatter.Deserialize(zipStream); } zipStream.Close(); } memStream.Close(); return (ISerializable)result; }