public override Package Read() { Package package = new Package(); package.Name = this.packageName; ZipInputStream zipInputStream = new ZipInputStream(this.input); ZipEntry nextEntry; while ((nextEntry = zipInputStream.GetNextEntry()) != null) { if (!nextEntry.IsDirectory) { byte[] numArray = new byte[nextEntry.Size]; int offset = 0; int length = numArray.Length; int num; do { num = ((Stream)zipInputStream).Read(numArray, offset, length); offset += num; length -= num; } while (num > 0); string path = nextEntry.Name.Replace('/', '\\').Trim(new char[] { '\\' }); this.AddEntry(package, path, numArray); } } return package; }
public static string[] getFiles( string zipFilename, string folderPath ) { List<string> fileList = new List<string>(); using (ZipInputStream inputStream = new ZipInputStream(File.OpenRead(zipFilename))) { ZipEntry entry; while ((entry = inputStream.GetNextEntry()) != null) { if ( entry.FileName.StartsWith( folderPath ) && !entry.IsDirectory ) { char[] charsToTrim = { '/' }; string entryFilename = entry.FileName.Substring( folderPath.Length ).Trim( charsToTrim ); //Message.Log("entryFilename: '" + entryFilename + "'" ); // Must not be a nested file in a subdirectory. int idx = entryFilename.LastIndexOf( "/" ); if ( idx < 0 ) { fileList.Add(entryFilename); } } } } return fileList.ToArray(); }
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); }
public static void unzipFolder( string zipFilename, string folderPath, string dstFolder ) { byte[] data = new byte[4096]; using (ZipInputStream inputStream = new ZipInputStream(File.OpenRead(zipFilename))) { ZipEntry entry; while ((entry = inputStream.GetNextEntry()) != null) { if ( entry.FileName.StartsWith( folderPath ) && !entry.IsDirectory ) { char[] charsToTrim = { '/' }; string entryName = entry.FileName.Substring( folderPath.Length ).Trim( charsToTrim ); string entryFilename = entryName; string entryFolder = dstFolder; int idx = entryFilename.LastIndexOf( "/" ); if ( idx >= 0 ) { entryFolder = dstFolder + "/" + entryFilename.Substring( 0, idx ); entryFilename = entryFilename.Substring( idx+1 ); } DirectoryInfo dirInfo = new DirectoryInfo(entryFolder); if ( !dirInfo.Exists ) { Directory.CreateDirectory( entryFolder ); } Message.Log( "Copying file to '" + entryFolder + "/" + entryFilename + "'" ); FileStream outputStream = new FileStream( entryFolder + "/" + entryFilename, FileMode.Create, FileAccess.Write ); int size = inputStream.Read( data, 0, data.Length ); while ( size > 0 ) { outputStream.Write( data, 0, size ); size = inputStream.Read( data, 0, data.Length ); } outputStream.Close(); } } } }
/// <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 static List <string> Unzip(byte[] fileData, string unzipDir) { //FastZip解压目录在Mac上有问题 // FastZipEvents ev = new FastZipEvents(); // ev.CompletedFile = OnCompletedFile; // (new FastZip(ev)).ExtractZip(sourceFile, Utility.LocalStoragePath, ""); //先存为临时文件,再一次性重命名至目标文件,减少处理一半的可能性 List <string> tmpFiles = new List <string>(); List <string> targetFiles = new List <string>(); List <string> entryNames = new List <string>(); if (readBuffer == null) { readBuffer = new byte[256 * 1024]; } int size = 0; ZipEntry entry = null; using (ZipInputStream zis = new ZipInputStream(new MemoryStream(fileData))) { while ((entry = zis.GetNextEntry()) != null) { string unzipPath = Path.Combine(unzipDir, entry.Name); string dirPath = Path.GetDirectoryName(unzipPath); if (!string.IsNullOrEmpty(dirPath)) { if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } } if (entry.IsFile) { string fileName = Path.GetFileName(unzipPath); string tmpPath = string.Format("{0}/{1}.tmp", dirPath, fileName); if (File.Exists(tmpPath)) { File.Delete(tmpPath); } using (FileStream streamWriter = File.Create(tmpPath)) { while (true) { size = zis.Read(readBuffer, 0, readBuffer.Length); if (size <= 0) { break; } streamWriter.Write(readBuffer, 0, size); } streamWriter.Close(); } targetFiles.Add(unzipPath); tmpFiles.Add(tmpPath); entryNames.Add(entry.Name); } } } for (int i = 0; i < targetFiles.Count; i++) { FileInfo info = new FileInfo(tmpFiles[i]); string targetFile = targetFiles[i]; if (File.Exists(targetFile)) { File.Delete(targetFile); } info.MoveTo(targetFile); } return(entryNames); }
private void ReadZipStream(Stream inputStream, bool isEmbeddedZip) { Log.StartJob(Util.FILES_Reading); var unzip = new ZipInputStream(inputStream); ZipEntry entry = unzip.GetNextEntry(); while (entry != null) { if (!entry.IsDirectory) { //Add file to list var file = new InstallFile(unzip, entry, this); if (file.Type == InstallFileType.Resources && (file.Name.ToLowerInvariant() == "containers.zip" || file.Name.ToLowerInvariant() == "skins.zip")) { //Temporarily save the TempInstallFolder string tmpInstallFolder = TempInstallFolder; //Create Zip Stream from File var zipStream = new FileStream(file.TempFileName, FileMode.Open, FileAccess.Read); //Set TempInstallFolder TempInstallFolder = Path.Combine(TempInstallFolder, Path.GetFileNameWithoutExtension(file.Name)); //Extract files from zip ReadZipStream(zipStream, true); //Restore TempInstallFolder TempInstallFolder = tmpInstallFolder; //Delete zip file var zipFile = new FileInfo(file.TempFileName); zipFile.Delete(); } else { Files[file.FullName.ToLower()] = file; if (file.Type == InstallFileType.Manifest && !isEmbeddedZip) { if (ManifestFile == null) { ManifestFile = file; } else { if (file.Extension == "dnn7" && (ManifestFile.Extension == "dnn" || ManifestFile.Extension == "dnn5" || ManifestFile.Extension == "dnn6")) { ManifestFile = file; } else if (file.Extension == "dnn6" && (ManifestFile.Extension == "dnn" || ManifestFile.Extension == "dnn5")) { ManifestFile = file; } else if (file.Extension == "dnn5" && ManifestFile.Extension == "dnn") { ManifestFile = file; } else if (file.Extension == ManifestFile.Extension) { Log.AddFailure((Util.EXCEPTION_MultipleDnn + ManifestFile.Name + " and " + file.Name)); } } } } Log.AddInfo(string.Format(Util.FILE_ReadSuccess, file.FullName)); } entry = unzip.GetNextEntry(); } if (ManifestFile == null) { Log.AddFailure(Util.EXCEPTION_MissingDnn); } if (Log.Valid) { Log.EndJob(Util.FILES_ReadingEnd); } else { Log.AddFailure(new Exception(Util.EXCEPTION_FileLoad)); Log.EndJob(Util.FILES_ReadingEnd); } //Close the Zip Input Stream as we have finished with it inputStream.Close(); }
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"); } } }
public void InvalidPasswordSeekable() { byte[] originalData = null; var compressedData = MakeInMemoryZip(ref originalData, CompressionMethod.Deflated, 3, 500, "Hola", true); var ms = new MemoryStream(compressedData); ms.Seek(0, SeekOrigin.Begin); var buf2 = new byte[originalData.Length]; var pos = 0; var inStream = new ZipInputStream(ms); inStream.Password = "******"; var entry2 = inStream.GetNextEntry(); while (true) { var numRead = inStream.Read(buf2, pos, buf2.Length); if (numRead <= 0) { break; } pos += numRead; } }
/// <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 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 CreateAndReadEmptyZip() { var ms = new MemoryStream(); var outStream = new ZipOutputStream(ms); outStream.Finish(); ms.Seek(0, SeekOrigin.Begin); var inStream = new ZipInputStream(ms); ZipEntry entry; while ((entry = inStream.GetNextEntry()) != null) { Assert.Fail("No entries should be found in empty zip"); } }
public void Stream_UnicodeEntries() { var ms = new MemoryStream(); using (var s = new ZipOutputStream(ms)) { s.IsStreamOwner = false; var sampleName = "\u03A5\u03d5\u03a3"; var sample = new ZipEntry(sampleName); sample.IsUnicodeText = true; s.PutNextEntry(sample); s.Finish(); ms.Seek(0, SeekOrigin.Begin); using (var zis = new ZipInputStream(ms)) { var ze = zis.GetNextEntry(); Assert.AreEqual(sampleName, ze.Name, "Expected name to match original"); Assert.IsTrue(ze.IsUnicodeText, "Expected IsUnicodeText flag to be set"); } } }
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(); }
public void PasswordCheckingWithDateInExtraData() { var ms = new MemoryStream(); var checkTime = new DateTime(2010, 10, 16, 0, 3, 28); using (var zos = new ZipOutputStream(ms)) { zos.IsStreamOwner = false; zos.Password = "******"; var ze = new ZipEntry("uno"); ze.DateTime = new DateTime(1998, 6, 5, 4, 3, 2); var zed = new ZipExtraData(); zed.StartNewEntry(); zed.AddData(1); var delta = checkTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime(); var seconds = (int) delta.TotalSeconds; zed.AddLeInt(seconds); zed.AddNewEntry(0x5455); ze.ExtraData = zed.GetEntryData(); zos.PutNextEntry(ze); zos.WriteByte(54); } ms.Position = 0; using (var zis = new ZipInputStream(ms)) { zis.Password = "******"; var uno = zis.GetNextEntry(); var theByte = (byte) zis.ReadByte(); Assert.AreEqual(54, theByte); Assert.AreEqual(-1, zis.ReadByte()); Assert.AreEqual(checkTime, uno.DateTime); } }
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(); } }
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 { } } }
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); } }
public void ParameterHandling() { var buffer = new byte[10]; var emptyBuffer = new byte[0]; var ms = new MemoryStream(); var outStream = new ZipOutputStream(ms); outStream.IsStreamOwner = false; outStream.PutNextEntry(new ZipEntry("Floyd")); outStream.Write(buffer, 0, 10); outStream.Finish(); ms.Seek(0, SeekOrigin.Begin); var inStream = new ZipInputStream(ms); var e = inStream.GetNextEntry(); MustFailRead(inStream, null, 0, 0); MustFailRead(inStream, buffer, -1, 1); MustFailRead(inStream, buffer, 0, 11); MustFailRead(inStream, buffer, 7, 5); MustFailRead(inStream, buffer, 0, -1); MustFailRead(inStream, emptyBuffer, 0, 1); var bytesRead = inStream.Read(buffer, 10, 0); Assert.AreEqual(0, bytesRead, "Should be able to read zero bytes"); bytesRead = inStream.Read(emptyBuffer, 0, 0); Assert.AreEqual(0, bytesRead, "Should be able to read zero bytes"); }
public statusWsTotal descargarTitulo(string numeroLote) { string errores = ""; int bandStatus = 0; //int status=0; string err = ""; byte[] archivoUnZip; //Procesos proc = new Procesos(); statusWs zipArchive = new statusWs(); EncodeDecode Encode = new EncodeDecode(); statusWsTotal resumen = new statusWsTotal(); string dMensaje = ""; string dNumLote = ""; byte[] dArchivo = null; // Servidor de Desarrollo ///* ServiceReferencePrueba.autenticacionType autenticacion2 = new ServiceReferencePrueba.autenticacionType(); ServiceReferencePrueba.TitulosPortTypeClient soap2 = new ServiceReferencePrueba.TitulosPortTypeClient(); ServiceReferencePrueba.descargaTituloElectronicoRequest dRequest2 = new ServiceReferencePrueba.descargaTituloElectronicoRequest(); ServiceReferencePrueba.descargaTituloElectronicoResponse dResponse2 = new ServiceReferencePrueba.descargaTituloElectronicoResponse(); autenticacion2.usuario = "usuariomet.qa794"; autenticacion2.password = "******"; //*/ string cNumLote = numeroLote; //DESCARGA DE TITULO// dRequest2.numeroLote = cNumLote; dRequest2.autenticacion = autenticacion2; // Esperamos cinco segundos para la respuesta //Thread.Sleep(5000); dResponse2 = soap2.descargaTituloElectronico(dRequest2); dMensaje = dResponse2.mensaje; dNumLote = dResponse2.numeroLote; dArchivo = dResponse2.titulosBase64; if (dArchivo == null) { string mensaje = "Error: Servicio DGP Documento: "; //+ doc + "Lote: " + dNumLote + " Mensaje Servidor: " + dMensaje; //string error = GrabaStObs(doc, 4, mensaje); resumen.errores += mensaje; return(resumen); } //UNZIP// using (var outputStream = new MemoryStream()) { using (var inputStream = new MemoryStream(dArchivo)) { using (var zipInputStream = new ZipInputStream(inputStream)) { zipInputStream.GetNextEntry(); zipInputStream.CopyTo(outputStream); } archivoUnZip = outputStream.ToArray(); //GUARDAR XLS File.WriteAllBytes(@"C:\Users\Luis\Documents\" + dNumLote + ".xls", archivoUnZip); } } //NUEVO LEER BYTES List <CamposXls> resunemXls = leerArchivoRespuesta(dNumLote); byte status = 0; string docxml; resumen.NumLote = dNumLote; foreach (CamposXls resp in resunemXls) { resumen.TotalTitulos += 1; switch (resp.Estatus) { case "1": resumen.Correctos += 1; status = 5; docxml = Regex.Replace(resp.Archivo, @"[^0-9]", "", RegexOptions.None); break; case "2": resumen.Fallidos += 1; status = 4; docxml = Regex.Replace(resp.Archivo, @"[^0-9]", "", RegexOptions.None); resumen.descripcion = resp.Descripcion; break; case " ": resumen.SinRespuesta += 1; status = 4; break; } //string error = GrabaStObs(doc, status, resp.Descripcion); // if (error.Length > 4 && error.Substring(0, 5) == "Error") // { // errores += "Error: No se pudo cambiar ST a registro en profesiones, del documento: " + doc; // } } //File.Delete(@"C:\Users\Luis\Documents\" + dNumLote + ".xls"); return(resumen); }
public void Error_UseZipEntryExtractWith_ZIS_wi10355() { string zipFileToCreate = "UseOpenReaderWith_ZIS.zip"; CreateSmallZip(zipFileToCreate); // mixing ZipEntry.Extract and ZipInputStream is a no-no!! string extractDir = "extract"; // Use ZipEntry.Extract with ZipInputStream. // This must fail. TestContext.WriteLine("Reading with ZipInputStream"); using (var zip = new ZipInputStream(zipFileToCreate)) { ZipEntry entry; while ((entry = zip.GetNextEntry()) != null) { entry.Extract(extractDir, Ionic.Zip.ExtractExistingFileAction.OverwriteSilently); } } }
public static void UnzipThread(string zipFilePath, string targetDir) { DirectoryInfo dir = new DirectoryInfo(targetDir); if (dir.Exists == false) { dir.Create(); } ZipFile zFile = new ZipFile(zipFilePath); TotalSize = 0; CurrentSize = 0; Stopwatch sw = Stopwatch.StartNew(); foreach (ZipEntry e in zFile) { TotalSize += e.Size; } zFile.Close(); Debug.LogWarning("计算压缩包大小=====>" + sw.ElapsedMilliseconds + "ms"); using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath))) { ZipEntry theEntry; while ((theEntry = s.GetNextEntry()) != null) { string directoryName = Path.GetDirectoryName(theEntry.Name); string fileName = Path.GetFileName(theEntry.Name); // create directory if (directoryName.Length > 0) { Directory.CreateDirectory(targetDir + "/" + directoryName); } if (fileName != String.Empty) { using (FileStream streamWriter = File.Create(targetDir + "/" + theEntry.Name)) { int size = 2048; byte[] data = new byte[size]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); CurrentSize += size; } else { break; } } } } } } Debug.LogWarning("ZipFile解压完成:" + zipFilePath + "\n解压目录" + targetDir); }
public void ExerciseGetNextEntry() { var compressedData = MakeInMemoryZip( true, new RuntimeInfo(CompressionMethod.Deflated, 9, 50, null, true), new RuntimeInfo(CompressionMethod.Deflated, 2, 50, null, true), new RuntimeInfo(CompressionMethod.Deflated, 9, 50, null, true), new RuntimeInfo(CompressionMethod.Deflated, 2, 50, null, true), new RuntimeInfo(null, true), new RuntimeInfo(CompressionMethod.Stored, 2, 50, null, true), new RuntimeInfo(CompressionMethod.Deflated, 9, 50, null, true) ); var ms = new MemoryStream(compressedData); ms.Seek(0, SeekOrigin.Begin); using (var inStream = new ZipInputStream(ms)) { var buffer = new byte[10]; ZipEntry entry; while ((entry = inStream.GetNextEntry()) != null) { // Read a portion of the data, so GetNextEntry has some work to do. inStream.Read(buffer, 0, 10); } } }
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; }
/// <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(); }
//利用SharpZipLib解压 /// <summary> /// 解压zip文件,文件夹和zip文件同名 /// </summary> /// <param name="zipFilePath">zip文件路径</param> /// <param name="unZipDir">解压文件存放路径,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹</param> /// <returns></returns> public static bool UnZipFileDictory(string zipFilePath, string unZipDir) { string error = ""; if (zipFilePath == string.Empty) { error = "压缩文件不能为空!"; return(false); } try { if (!File.Exists(zipFilePath)) { error = "压缩文件不存在!"; return(false); } ////解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹 if (string.IsNullOrEmpty(unZipDir)) { unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath)); } if (!unZipDir.EndsWith("//")) { unZipDir += "//"; } if (!Directory.Exists(unZipDir)) { Directory.CreateDirectory(unZipDir); } else { Directory.Delete(unZipDir, true); Directory.CreateDirectory(unZipDir); } using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath))) { ZipEntry theEntry; while ((theEntry = s.GetNextEntry()) != null) { string directoryName = Path.GetDirectoryName(theEntry.Name); string fileName = Path.GetFileName(theEntry.Name); if (directoryName.Length > 0) { Directory.CreateDirectory(unZipDir + directoryName); } if (!directoryName.EndsWith("//")) { directoryName += "//"; } if (!string.IsNullOrEmpty(fileName)) { using (FileStream streamWriter = File.Create(unZipDir + 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; } } } } }//while } } catch (Exception ex) { error = ex.Message; return(false); } return(true); }
/// ----------------------------------------------------------------------------- /// <summary> /// The InstallFile method installs a single assembly. /// </summary> /// <param name = "insFile">The InstallFile to install</param> protected override bool InstallFile(InstallFile insFile) { bool retValue = true; try { Log.AddInfo(Util.FILES_Expanding); //Create the folder for destination _Manifest = insFile.Name + ".manifest"; if (!Directory.Exists(PhysicalBasePath)) { Directory.CreateDirectory(PhysicalBasePath); } using (var unzip = new ZipInputStream(new FileStream(insFile.TempFileName, FileMode.Open))) using (var manifestStream = new FileStream(Path.Combine(PhysicalBasePath, Manifest), FileMode.Create, FileAccess.Write)) { var settings = new XmlWriterSettings(); settings.ConformanceLevel = ConformanceLevel.Fragment; settings.OmitXmlDeclaration = true; settings.Indent = true; using (var writer = XmlWriter.Create(manifestStream, 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) { entry.CheckZipEntry(); 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); var 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; } return(retValue); }
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 = string.Empty; 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) { objZipEntry.CheckZipEntry(); 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); }
/// <summary> /// 功能:解压 zip格式的文件。 /// </summary> /// <param name="zipFilePath"> 压缩文件路径 </param> /// <param name="unZipDir"> 解压文件存放路径 ,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹 </param> public static void UnZipFile(string zipFilePath, string unZipDir) { if (zipFilePath == string.Empty) { throw new ArgumentException("压缩文件不能为空"); } if (!File.Exists(zipFilePath)) { throw new ArgumentException("压缩文件不存在"); } //解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹 if (unZipDir == string.Empty) { unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath)); } if (!unZipDir.EndsWith("\\")) { unZipDir += "\\"; } if (!Directory.Exists(unZipDir)) { Directory.CreateDirectory(unZipDir); } try { using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath))) { ZipEntry theEntry; while ((theEntry = s.GetNextEntry()) != null) { string directoryName = Path.GetDirectoryName(theEntry.Name); string fileName = Path.GetFileName(theEntry.Name); if (directoryName.Length > 0) { Directory.CreateDirectory(unZipDir + directoryName); } if (!directoryName.EndsWith("\\")) { directoryName += "\\"; } if (fileName != String.Empty) { using (FileStream streamWriter = File.Create(unZipDir + 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; } } } } } //while } } catch (Exception ex) { throw new Exception("压缩出现错误:" + ex.Message); } } //解压结束
/// <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); }
/// <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 void UnZip(string zipFilePath, string unZipDir) { if (zipFilePath == string.Empty) { throw new Exception("压缩文件不能为空!"); } if (!File.Exists(zipFilePath)) { throw new FileNotFoundException("压缩文件不存在!"); } //解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹 if (unZipDir == string.Empty) { unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath)); } if (!unZipDir.EndsWith("/")) { unZipDir += "/"; } if (!Directory.Exists(unZipDir)) { Directory.CreateDirectory(unZipDir); } using (var s = new ZipInputStream(File.OpenRead(zipFilePath))) { ZipEntry theEntry; while ((theEntry = s.GetNextEntry()) != null) { string directoryName = Path.GetDirectoryName(theEntry.Name); string fileName = Path.GetFileName(theEntry.Name); if (!string.IsNullOrEmpty(directoryName)) { Directory.CreateDirectory(unZipDir + directoryName); } if (directoryName != null && !directoryName.EndsWith("/")) { } if (fileName != String.Empty) { using (FileStream streamWriter = File.Create(unZipDir + theEntry.Name)) { int size; byte[] data = new byte[2048]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { 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 == null) { throw (new InvalidDataException("The file is not an valid Package file. If the file is encrypted, please supply the password in the constructor.")); } 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 = RecyclableMemoryStream.GetStream(); 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> /// Extract firmware image from downloaded zip file. /// </summary> private void ExtractFirmware() { string funcMsg = Name + ".ExtractFirmware: "; Master.Instance.ConsoleService.UpdateAction(ConsoleServiceResources.EXTRACTING); Log.Debug(string.Format("{0}Extracting contents of {1} byte zip file", funcMsg, FirmwareUpgrade.Firmware.Length)); DateTime startTime = DateTime.UtcNow; try { using (MemoryStream memStream = new MemoryStream(FirmwareUpgrade.Firmware, false)) { // System.IO.Packaging.ZipPackage can handle .zip files, but it is not supported in Compact Framework. // We therefore use the freeware SharpZipLib to do our uncompression. using (ZipInputStream s = new ZipInputStream(memStream)) { ZipEntry zipEntry; while ((zipEntry = s.GetNextEntry()) != null) { Log.Debug(string.Format("{0}ZipEntry Name=\"{1}\", Compressed size={2}, Uncompressed size={3}", funcMsg, zipEntry.Name, zipEntry.CompressedSize, zipEntry.Size)); string fileName = Path.GetFileName(zipEntry.Name); if (fileName == String.Empty) { continue; } // Skip zipped files that aren't the actual OS image. if (string.Compare(fileName.ToLower(), IMAGE_FILE_NAME) != 0) { continue; } // Note that we set the capacity of the memorystream to EXACTLY the size of the // deflated file. This solves two problems: 1) It prevents excessive memory // growth as we write the memorystream (e.g., a 2MB firmware file may cause // the capacity to grow to as much as 4MB if we didn't cap it), and 2) // it allows us to call GetBuffer() on the MemoryStream later and get back // the exact contents of the extracted file instead of having to do a ToArray() // call on it to get the exact file by doing a whole copy of the stream's // internal buffer using (MemoryStream unzippedStream = new MemoryStream((int)zipEntry.Size)) { byte[] buf = new byte[8192]; while (true) { int size = s.Read(buf, 0, buf.Length); if (size <= 0) { break; } unzippedStream.Write(buf, 0, size); } _firmwareFile = unzippedStream; } break; } // end-while GetNextEntry } // end-using ZipInputStream } // end-using MemoryStream } catch (Exception e) { throw new FirmwareUpgradeException("Error unzipping firmware upgrade.", e); } TimeSpan elapsed = DateTime.UtcNow - startTime; Log.Debug(string.Format("{0}Extraction finished in {1} seconds.", funcMsg, elapsed.TotalSeconds)); if (_firmwareFile == null) { throw new FirmwareUpgradeException(string.Format("No \"{0}\" file found inside downloaded firmware upgrade file.", IMAGE_FILE_NAME)); } }
/// <summary> /// 압축 파일 풀기 /// </summary> /// <param name="zipFilePath">ZIP파일 경로</param> /// <param name="unZipTargetFolderPath">압축 풀 폴더 경로</param> /// <param name="password">해지 암호</param> /// <param name="isDeleteZipFile">zip파일 삭제 여부</param> /// <returns>압축 풀기 성공 여부 </returns> public static Boolean Unzip(String zipFilePath, String unZipTargetFolderPath, String password, Boolean isDeleteZipFile) { Boolean 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 (Exception) { retVal = false; } finally { // ZIP 파일 스트림 종료 zipInputStream.Close(); } // ZIP파일 삭제를 원할 경우 파일 삭제. if (isDeleteZipFile) { try { File.Delete(zipFilePath); } catch { } } } return(retVal); }
public void InstallForge(string mcversion, string forgeversion) { FileChanged?.Invoke(new DownloadFileChangedEventArgs() { FileKind = MFile.Library, FileName = "installer", ProgressedFileCount = 0, TotalFileCount = 2 }); var versionname = $"{mcversion}-forge{mcversion}-{forgeversion}"; var manifest = Path.Combine( Minecraft.Versions, versionname, versionname + ".json" ); var installer = $"{MavenServer}{mcversion}-{forgeversion}/forge-{mcversion}-{forgeversion}-installer.jar"; var jsondata = new StringBuilder(); var res = WebRequest.Create(installer).GetResponse().GetResponseStream(); using (res) using (var s = new ZipInputStream(res)) { ZipEntry e; while ((e = s.GetNextEntry()) != null) { if (!e.IsFile || e.Name != "install_profile.json") { continue; } var buffer = new byte[1024]; while (true) { int size = s.Read(buffer, 0, buffer.Length); if (size == 0) { break; } jsondata.Append(Encoding.UTF8.GetString(buffer, 0, size)); } } } if (jsondata.Length == 0) { throw new Exception("can't find profile file"); } var libraries = JObject.Parse(jsondata.ToString())["versionInfo"]; FileChanged?.Invoke(new DownloadFileChangedEventArgs() { FileKind = MFile.Library, FileName = "universal", ProgressedFileCount = 1, TotalFileCount = 2 }); var universalUrl = $"{MavenServer}{mcversion}-{forgeversion}/forge-{mcversion}-{forgeversion}-universal.jar"; var dest = Path.Combine( Minecraft.Library, "net", "minecraftforge", "forge", $"{mcversion}-{forgeversion}", $"forge-{mcversion}-{forgeversion}.jar" ); Directory.CreateDirectory(Path.GetDirectoryName(dest)); var downloader = new WebDownload(); downloader.DownloadFile(universalUrl, dest); Directory.CreateDirectory(Path.GetDirectoryName(manifest)); File.WriteAllText(manifest, libraries.ToString()); FileChanged?.Invoke(new DownloadFileChangedEventArgs() { FileKind = MFile.Library, FileName = "universal", ProgressedFileCount = 2, TotalFileCount = 2 }); }
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); } }
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()); } }
public async Task UpdatePlants(CancellationToken token) { if (imageFilesToDownload.Count > 0) { try { long receivedBytes = 0; long?totalBytes = imageFilesToDownload.Sum(x => x.valueint); await progressBar.ProgressTo(0, 1, Easing.Linear); downloadLabel.Text = "Beginning Download..."; //Downlod Plant Data //await Task.Run(() => { UpdatePlantConcurrently(token); }); await UpdatePlantConcurrently(token); // IFolder interface from PCLStorage; create or open imagesZipped folder (in Library/Images) IFolder folder = await rootFolder.CreateFolderAsync("Images", CreationCollisionOption.OpenIfExists); string folderPath = rootFolder.Path; // Get image file setting records from MobileApi to determine which files to download // TODO: Limit this to only the files needed, not just every file totalBytes = imageFilesToDownload.Sum(x => x.valueint); // For each setting, get the corresponding zip file and save it locally foreach (WoodySetting imageFileToDownload in imageFilesToDownload) { if (token.IsCancellationRequested) { break; } ; Stream webStream = await externalConnection.GetImageZipFiles(imageFileToDownload.valuetext.Replace(".zip", "")); ZipInputStream zipInputStream = new ZipInputStream(webStream); ZipEntry zipEntry = zipInputStream.GetNextEntry(); while (zipEntry != null) { if (token.IsCancellationRequested) { break; } ; //token.ThrowIfCancellationRequested(); String entryFileName = zipEntry.Name; // to remove the folder from the entry:- entryFileName = Path.GetFileName(entryFileName); // Optionally match entrynames against a selection list here to skip as desired. byte[] buffer = new byte[4096]; IFile file = await folder.CreateFileAsync(entryFileName, CreationCollisionOption.OpenIfExists); using (Stream localStream = await file.OpenAsync(FileAccess.ReadAndWrite)) { StreamUtils.Copy(zipInputStream, localStream, buffer); } receivedBytes += zipEntry.Size; //Double percentage = (((double)plantsSaved * 100000) + (double)receivedBytes) / (((plants.Count + terms.Count) * 100000) + (double)totalBytes); Double percentage = ((double)receivedBytes / (double)totalBytes); await progressBar.ProgressTo(percentage, 1, Easing.Linear); zipEntry = zipInputStream.GetNextEntry(); if (Math.Round(percentage * 100) < 100) { downloadLabel.Text = "Downloading Plant Data..." + Math.Round(percentage * 100) + "%"; } else { downloadLabel.Text = "Finishing Download..."; } } if (!token.IsCancellationRequested) { //downloadImages = true; await App.WoodySettingsRepo.AddSettingAsync(new WoodySetting { name = "ImagesZipFile", valuebool = true }); await App.WoodySettingsRepo.AddSettingAsync(new WoodySetting { name = "ImagesZipFile", valuetimestamp = imageFileToDownload.valuetimestamp, valuetext = imageFileToDownload.valuetext }); // App.WoodyPlantImageRepoLocal = new WoodyPlantImageRepositoryLocal(App.WoodyPlantImageRepo.GetAllWoodyPlantImages()); } } } catch (OperationCanceledException e) { Debug.WriteLine("Canceled Downloading of Images {0}", e.Message); } catch (Exception e) { Debug.WriteLine("ex {0}", e.Message); } } }
//LAMADA AL WEB SERVICE// //public string mandarWs(int doc, int id_usuario, string sello, string preAutentXml ) public string mandarWs(int doc, string sello, string prXml) { string errores = ""; int bandStatus = 0; //int status=0; string err = ""; byte[] archivoUnZip; //Procesos proc = new Procesos(); statusWs zipArchive = new statusWs(); EncodeDecode Encode = new EncodeDecode(); //string xML = db.XMLs.Where(x => x.ID_DOCUMENTO == doc).FirstOrDefault().XML_STR; string xML = prXml; //ENCODE string encode = Encode.Base64Encode(xML); byte[] bytes = System.Convert.FromBase64String(encode); string dMensaje = ""; string dNumLote = ""; byte[] dArchivo = null; // Servidor de Desarrollo ///* ServiceReferencePrueba.autenticacionType autenticacion2 = new ServiceReferencePrueba.autenticacionType(); ServiceReferencePrueba.TitulosPortTypeClient soap2 = new ServiceReferencePrueba.TitulosPortTypeClient(); ServiceReferencePrueba.cargaTituloElectronicoRequest cRequest2 = new ServiceReferencePrueba.cargaTituloElectronicoRequest(); ServiceReferencePrueba.cargaTituloElectronicoResponse cResponse2 = new ServiceReferencePrueba.cargaTituloElectronicoResponse(); ServiceReferencePrueba.descargaTituloElectronicoRequest dRequest2 = new ServiceReferencePrueba.descargaTituloElectronicoRequest(); ServiceReferencePrueba.descargaTituloElectronicoResponse dResponse2 = new ServiceReferencePrueba.descargaTituloElectronicoResponse(); autenticacion2.usuario = "usuariomet.qa794"; autenticacion2.password = "******"; //*/ //CARGA DE TITULO EN SERVIDOR DE DESARROLLO// cRequest2.nombreArchivo = (doc + ".xml").ToString(); cRequest2.archivoBase64 = bytes; cRequest2.autenticacion = autenticacion2; cResponse2 = soap2.cargaTituloElectronico(cRequest2); string cNumLote = cResponse2.numeroLote; //DESCARGA DE TITULO// dRequest2.numeroLote = cNumLote; dRequest2.autenticacion = autenticacion2; // Esperamos cinco segundos para la respuesta Thread.Sleep(5000); dResponse2 = soap2.descargaTituloElectronico(dRequest2); dMensaje = dResponse2.mensaje; dNumLote = dResponse2.numeroLote; dArchivo = dResponse2.titulosBase64; if (dArchivo == null) { string mensaje = "Error: Servicio DGP Documento: " + doc + "Lote: " + dNumLote + " Mensaje Servidor: " + dMensaje; string error = GrabaStObs(doc, 4, mensaje); errores += mensaje; return(errores); } //UNZIP// using (var outputStream = new MemoryStream()) { using (var inputStream = new MemoryStream(dArchivo)) { using (var zipInputStream = new ZipInputStream(inputStream)) { zipInputStream.GetNextEntry(); zipInputStream.CopyTo(outputStream); } archivoUnZip = outputStream.ToArray(); //GUARDAR XLS //File.WriteAllBytes(@"C:\Users\Desktop\ss.xls", dd); } } //LEER DATOS DENTRO DE XLS MemoryStream ms = new MemoryStream(archivoUnZip); Encoding codificacion = Encoding.Default; StreamReader sr = new StreamReader(ms, codificacion); string linea; int i = 0; while ((linea = sr.ReadLine()) != null) { i = i + 1; string lin = linea; if (lin.Contains("exitosamente")) { bandStatus = 1; zipArchive.status = bandStatus; zipArchive.descripcion = "Título electrónico registrado exitosamente. Lote: " + dNumLote; } else { if (lin.Contains("FOLIO")) { err = lin; zipArchive.descripcion = Regex.Replace(err, @"[^0-9A-Za-z.:,áéíóúÁÉÍÓÚ]", " ", RegexOptions.None) + " Lote: " + dNumLote; zipArchive.status = 2; } } } sr.Close(); //CAMBIO ESTATUS DE TITULO// //CAMBIAR ESTATUS //if (zipArchive.status == 1) //{ // string error = GrabaStObs(doc, 5, zipArchive.descripcion); // if (error.Length > 4 && error.Substring(0, 5) == "Error") // { // errores += "Error: No se pudo cambiar ST a registro en profesiones, del documento: " + doc; // } // //ACTUALIZAR XML EN TABLA .. excepto Normales ... // if (preAutentXml.Length > 0) // { // string docXml = preAutentXml; // try // { // XML tXML = db.XMLs.Where(x => x.ID_DOCUMENTO == doc).FirstOrDefault(); // if (tXML.XML_STR != docXml) // { // tXML.XML_STR = docXml; // db.Entry(tXML).State = EntityState.Modified; // db.SaveChanges(); // } // } // catch (Exception) // { // //Error no se pudo actualizar Xml // errores += "Error \t -(22) " + db.CAT_ERROR_MENSAJE.Find(22).DESCRIPCION + " \r\n"; // return (errores); // } // } // // Guarda Sello Documento IEA // db.SELLO_DOCUMENTO_IEA.Add(new SELLO_DOCUMENTO_IEA // { // ID_DOCUMENTO = doc, // ID_TIPOSELLADO = 3, // TXT_SELLO_DOCUMENTO_IEA = sello, // ID_ESTATUS_SELLO = 1, // FECHA_REGISTRO = DateTime.Now // }); // try { db.SaveChanges(); } // catch (Exception) // { // // return Conflict(); // errores += "Error: No se pudo actualizar Tabla SELLO_DOCUMENTO_IEA, documento: " + doc; // } // //BITACORA// // int moov = 5; // proc.GuardaBitacora(doc, (byte)moov, id_usuario); //} //else //{ // string error = GrabaStObs(doc, 4, zipArchive.descripcion); // errores += "Error: " + zipArchive.descripcion; // //BITACORA// // int moov = 9; // proc.GuardaBitacora(doc, (byte)moov, id_usuario); //} if (errores.Length == 0 && zipArchive.descripcion.Length > 0) { errores = zipArchive.descripcion; } return(errores); }
/// <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> /// 解压功能(解压压缩文件到指定目录) /// </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); }
/// <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); } }
/// <summary> /// Function to Unzipp all the File From Zip File /// </summary> /// <param name="ZipFile"></param> /// <param name="DestinationDir"></param> /// <returns></returns> public string UnzipFiles(string zipFile, string destinationDir, out int totalFiles) { string tempZipFilePath = destinationDir + "\\" + Path.GetFileName(zipFile); string fileName = string.Empty; ZipEntry theEntry = null; //Create directory if it doesn't exist and then copy file there and then extract if (!Directory.Exists(destinationDir)) { Directory.CreateDirectory(destinationDir); } File.Copy(zipFile, tempZipFilePath, true); totalFiles = 0; //We will just count the number of files which are there try { using (ZipInputStream streamInput = new ZipInputStream(File.OpenRead(tempZipFilePath))) { while ((theEntry = streamInput.GetNextEntry()) != null) { totalFiles++; } } if (totalFiles > 1) { totalFiles = 100001; return(null); } using (ZipInputStream streamInput = new ZipInputStream(File.OpenRead(tempZipFilePath))) { while ((theEntry = streamInput.GetNextEntry()) != null) { fileName = Path.GetFileName(theEntry.Name); if (fileName != String.Empty) { using (FileStream streamWriter = File.Create(destinationDir + "\\" + theEntry.Name)) { int size = 2048; byte[] data = new byte[2048]; while (true) { size = streamInput.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } } } } } return(destinationDir + "\\" + fileName); } catch { totalFiles = 0; return(null); } finally { if (File.Exists(tempZipFilePath)) { File.Delete(tempZipFilePath); } } }
/// <summary> /// 解压缩文件夹 /// </summary> /// <param name="path"></param> /// <returns></returns> #region public static bool unZipFile(String path) public static bool unZipFile(String path) { bool result = false; if (!File.Exists(path)) { Logger.info(typeof(ZipHelper), "file not exists."); return(result); } try { using (ZipInputStream zis = new ZipInputStream(File.OpenRead(path))) { ZipEntry entry; while ((entry = zis.GetNextEntry()) != null) { Logger.info(typeof(ZipHelper), String.Format("unzip {0}", entry.Name)); string directoryName = Path.GetDirectoryName(entry.Name); string fileName = Path.GetFileName(entry.Name); if (directoryName.Length > 0) { Directory.CreateDirectory(String.Format(@"back\{0}", directoryName)); } if (!String.IsNullOrEmpty(fileName)) { using (FileStream fis = File.Create(String.Format(@"back\{0}", entry.Name))) { byte[] data = new byte[1024 * 10]; while (true) { int size = zis.Read(data, 0, data.Length); if (size > 0) { fis.Write(data, 0, size); } else { break; } } } } } } result = true; } catch (IOException ex) { Logger.error(typeof(ZipHelper), ex); } catch (NotSupportedException ex) { Logger.error(typeof(ZipHelper), ex); } catch (Exception ex) { Logger.error(typeof(ZipHelper), ex); } return(result); }
public static string[] getDirectories( string zipFilename, string folderPath ) { List<string> dirList = new List<string>(); using (ZipInputStream inputStream = new ZipInputStream(File.OpenRead(zipFilename))) { ZipEntry entry; while ((entry = inputStream.GetNextEntry()) != null) { if ( entry.FileName.StartsWith( folderPath ) ) { char[] charsToTrim = { '/' }; string entryName = entry.FileName.Substring( folderPath.Length ).Trim( charsToTrim ); //Message.Log("entryName: '" + entryName + "'" ); // extract first directory. int idx = entryName.IndexOf( "/" ); if ( idx >= 0 ) { string dirEntry = entryName.Substring( 0, idx ); if ( !dirList.Contains( dirEntry ) ) dirList.Add( entryName.Substring( 0, idx ) ); } } } } return dirList.ToArray(); }
public static IEnumerator Unzip(string zipFilePath, string targetDir, Action <float> onProgress, int frameBuffer = 2 * 1024 * 1024) { Debug.LogWarning("frameBuffer==========>" + frameBuffer); DirectoryInfo dir = new DirectoryInfo(targetDir); if (dir.Exists == false) { dir.Create(); } ZipFile zFile = new ZipFile(zipFilePath); int fileCount = zFile.Size; int count = 0; long sizeCount = 0; using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath))) { ZipEntry theEntry; while ((theEntry = s.GetNextEntry()) != null) { Console.WriteLine(theEntry.Name); string directoryName = Path.GetDirectoryName(theEntry.Name); string fileName = Path.GetFileName(theEntry.Name); // create directory if (directoryName.Length > 0) { Directory.CreateDirectory(targetDir + "/" + directoryName); } if (fileName != String.Empty) { using (FileStream streamWriter = File.Create(targetDir + "/" + theEntry.Name)) { int size = 2048; byte[] data = new byte[size]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) { try { streamWriter.Write(data, 0, size); } catch (IOException e) { Debug.LogError("IOException=>" + e.Message); onProgress?.Invoke(-1); yield break; } } else { break; } sizeCount += size; } } } count++; if (sizeCount > frameBuffer) { onProgress?.Invoke((float)count / fileCount); sizeCount = 0; yield return(null); } } } onProgress?.Invoke(1); Debug.LogWarning("ZipFile解压完成:" + zipFilePath + "\n解压目录" + targetDir); }
public void Error_UseOpenReaderWith_ZIS_wi10923() { string zipFileToCreate = "UseOpenReaderWith_ZIS.zip"; CreateSmallZip(zipFileToCreate); // mixing OpenReader and ZipInputStream is a no-no!! int n; var buffer = new byte[2048]; // Use OpenReader with ZipInputStream. // This must fail. TestContext.WriteLine("Reading with ZipInputStream"); using (var zip = new ZipInputStream(zipFileToCreate)) { ZipEntry entry; while ((entry = zip.GetNextEntry()) != null) { TestContext.WriteLine(" Entry: {0}", entry.FileName); using (Stream file = entry.OpenReader()) { while((n= file.Read(buffer,0,buffer.Length)) > 0) ; } TestContext.WriteLine(" -- OpenReader() is done. "); } } }
private void ExerciseZip(CompressionMethod method, int compressionLevel, int size, string password, bool canSeek) { byte[] originalData = null; var compressedData = MakeInMemoryZip(ref originalData, method, compressionLevel, size, password, canSeek); var ms = new MemoryStream(compressedData); ms.Seek(0, SeekOrigin.Begin); using (var inStream = new ZipInputStream(ms)) { var decompressedData = new byte[size]; if (password != null) { inStream.Password = password; } var entry2 = inStream.GetNextEntry(); if ((entry2.Flags & 8) == 0) { Assert.AreEqual(size, entry2.Size, "Entry size invalid"); } var currentIndex = 0; if (size > 0) { var count = decompressedData.Length; while (true) { var numRead = inStream.Read(decompressedData, currentIndex, count); if (numRead <= 0) { break; } currentIndex += numRead; count -= numRead; } } Assert.AreEqual(currentIndex, size, "Original and decompressed data different sizes"); if (originalData != null) { for (var i = 0; i < originalData.Length; ++i) { Assert.AreEqual(decompressedData[i], originalData[i], "Decompressed data doesnt match original, compression level: " + compressionLevel); } } } }