private void WriteFolder(ZipOutputStream zipStream, string path, PackageFolder folder) { foreach (PackageEntry packageEntry in (IEnumerable<PackageEntry>) folder.GetEntries()) { if (packageEntry is PackageFile) { zipStream.PutNextEntry(new ZipEntry(this.CombinePath(path, packageEntry.Name))); byte[] data = ((PackageFile)packageEntry).Data; ((Stream)zipStream).Write(data, 0, data.Length); zipStream.CloseEntry(); } if (packageEntry is PackageFolder) this.WriteFolder(zipStream, this.CombinePath(path, packageEntry.Name), (PackageFolder)packageEntry); } }
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"); } } }
protected void btndownloadall_ServerClick(object sender, EventArgs e) { string ZipfileName = ""; if (hfdperid.Value != "0") { ZipfileName = "Wellness Documents For - " + hfdperid.Value + ".Zip"; } else { ZipfileName = "MyZipFiles.Zip"; } Response.ContentType = "application/zip"; Response.AddHeader("Content-Disposition", "filename=" + ZipfileName); byte[] buffer = new byte[4098]; ZipOutputStream ZipOutStream = new ZipOutputStream(Response.OutputStream); ZipOutStream.SetLevel(3); try { List <USP_GetWellnessDocumentsResult> Getdocuments = Person_Details.Licensing_Details.GetAllWellnessDocuments(Convert.ToInt32(hfdperid.Value)); foreach (var i in Getdocuments.ToList()) { string docmonth = ""; string docpath = ""; string docyear = i.docpath.Substring(39, 4); if (Convert.ToDateTime(i.Document_Date).Month < 10) { docmonth = i.docpath.Substring(44, 1); docpath = i.docpath.Substring(46); } else { docmonth = i.docpath.Substring(44, 2); docpath = i.docpath.Substring(47); } string filepath = System.Configuration.ConfigurationManager.AppSettings["docpath"].ToString() + "\\" + docyear + "\\" + docmonth + "\\" + docpath; Stream fs = File.OpenRead(filepath); ZipEntry zipentry = new ZipEntry(ZipEntry.CleanName(i.Filename)); zipentry.Size = fs.Length; ZipOutStream.PutNextEntry(zipentry); int count = fs.Read(buffer, 0, buffer.Length); while (count > 0) { ZipOutStream.Write(buffer, 0, count); count = fs.Read(buffer, 0, buffer.Length); if (!Response.IsClientConnected) { break; } Response.Flush(); } fs.Close(); } ZipOutStream.Close(); Response.Flush(); Response.End(); } catch (Exception ex) { throw ex; } }
public static bool CreateZipFile(string[] FileList, string[] newFileNameList, string ZipName, int ZipLevel) { try { // 'using' statements gaurantee the stream is closed properly which is a big source // of problems otherwise. Its exception safe as well which is great. if (File.Exists(ZipName)) { File.Delete(ZipName); } string directoryName = ZipName.Substring(0, ZipName.LastIndexOf('\\')); if (!Directory.Exists(directoryName)) { Log.Debug("Directory " + directoryName + " not found"); //Directory.CreateDirectory(directoryName); } using (ZipOutputStream s = new ZipOutputStream(File.Create(ZipName))) { s.SetLevel(ZipLevel); // 0 - store only to 9 - means best compression for (int i = 0; i < FileList.Length; i++) { if (FileList[i] == null || !File.Exists(FileList[i])) { continue; } using (FileStream fs = new FileStream(FileList[i], FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { if (fs.Length <= 0) { fs.Close(); continue; } // im Normalfall allokiert man die Buffer im voraus // hier aus Klarheitsgründen pro Datei einmal byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); fs.Close(); // und jetzt schreiben wir einen ZipEntry & die Daten // ZipEntry entry = new ZipEntry(FileList[i].Substring(FileList[i].LastIndexOf("\\") + 1)); if (String.IsNullOrEmpty(newFileNameList[i])) { newFileNameList[i] = FileList[i].Substring(FileList[i].LastIndexOf('\\') + 1); } ZipEntry entry = new ZipEntry(newFileNameList[i]);//ZipEntry entry = new ZipEntry(FileList[i]); s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); } } s.Finish(); s.Close(); } return(true); } catch (Exception ex) { Log.Error("Exception during zipping files:\n", ex); return(false); } }
/** * Save the specified part. * * @throws OpenXml4NetException * Throws if an internal exception is thrown. */ public bool Marshall(PackagePart part, Stream os) { if (!(os is ZipOutputStream)) { logger.Log(POILogger.ERROR, "Unexpected class " + os.GetType().Name); throw new OpenXml4NetException("ZipOutputStream expected !"); // Normally should happen only in developement phase, so just throw // exception } // check if there is anything to save for some parts. We don't do this for all parts as some code // might depend on empty parts being saved, e.g. some unit tests verify this currently. if (part.Size == 0 && part.PartName.Name.Equals("/xl/sharedStrings.xml")) { return(true); } ZipOutputStream zos = (ZipOutputStream)os; string name = ZipHelper .GetZipItemNameFromOPCName(part.PartName.URI .OriginalString); ZipEntry partEntry = new ZipEntry(name); try { // Create next zip entry zos.PutNextEntry(partEntry); // Saving data in the ZIP file Stream ins = part.GetInputStream(); byte[] buff = new byte[ZipHelper.READ_WRITE_FILE_BUFFER_SIZE]; int totalRead = 0; while (true) { int resultRead = ins.Read(buff, 0, buff.Length); if (resultRead == 0) { // End of file reached break; } zos.Write(buff, 0, resultRead); totalRead += resultRead; } zos.CloseEntry(); } catch (IOException ioe) { logger.Log(POILogger.ERROR, "Cannot write: " + part.PartName + ": in ZIP", ioe); return(false); } // Saving relationship part if (part.HasRelationships) { PackagePartName relationshipPartName = PackagingUriHelper .GetRelationshipPartName(part.PartName); MarshallRelationshipPart(part.Relationships, relationshipPartName, zos); } return(true); }
/// <summary> /// Adds the file specified in <paramref name="filePath"/> to the ZIP archive. If <paramref name="fileNameForZip"/> /// is specified, use that filename as the name of the file in the ZIP archive. /// </summary> /// <param name="zos">The ZipOutputStream (ZIP archive) the media object file is to be added to.</param> /// <param name="filePath">The full path to the media object file to be added to the ZIP archive. /// Ex: C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\desert sunsets\zOpt_sonorandesert.jpg</param> /// <param name="fileNameForZip">The full path to the file whose name is to be used to name the file specified /// by <paramref name="filePath"/> in the ZIP archive. If null or empty, the actual filename is used. This path /// does not have to refer to an existing file on disk, but it must begin with <paramref name="basePath"/>. /// Ex: C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\desert sunsets\sonorandesert.jpg</param> /// <param name="basePath">The full path to the directory containing the highest-level media file to be added /// to the ZIP archive. Must include trailing slash. Ex: C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\</param> /// <param name="isImage">Indicates whether the file specified in <paramref name="filePath"/> is an image. If it /// is, and <paramref name="applyWatermark"/> is <c>true</c>, a watermark is applied to the image as it is inserted /// into the archive.</param> /// <param name="applyWatermark">Indicates whether to apply a watermark to images as they are added to the archive. /// Applies only when <paramref name="isImage"/> is <c>true</c>.</param> private static void AddFileZipEntry(ZipOutputStream zos, string filePath, string fileNameForZip, string basePath, bool isImage, bool applyWatermark) { int bufferSize = Configuration.ConfigManager.GetGalleryServerProConfigSection().Core.MediaObjectDownloadBufferSize; byte[] buffer = new byte[bufferSize]; #region Determine ZIP entry name // Get name of the file as it will be stored in the ZIP archive. This is the fragment of the full file path // after the base path. Ex: If basePath="C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\" // and filePath="C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\desert sunsets\zOpt_sonorandesert.jpg", // then zipEntryName="desert sunsets\zOpt_sonorandesert.jpg". The ZIP algorithm will automatically sense the // embedded directory ("desert sunsets") and create it. string zipEntryName; if (String.IsNullOrEmpty(fileNameForZip)) { zipEntryName = filePath.Replace(basePath, String.Empty); } else { zipEntryName = fileNameForZip.Replace(basePath, String.Empty); } #endregion using (Stream stream = CreateStream(filePath, isImage, applyWatermark)) { ZipEntry entry = new ZipEntry(zipEntryName); entry.Size = stream.Length; zos.PutNextEntry(entry); int byteCount; while ((byteCount = stream.Read(buffer, 0, buffer.Length)) > 0) { zos.Write(buffer, 0, byteCount); } } }
public static void Main(string[] args) { String imageZipPassword = "******"; String dataDirectory = "/Users/tmt/Projects/sample/DotNetZip/data/"; String[] imageFileNames = { "image1.JPG" , "image2.JPG" }; String[] imagePaths = { dataDirectory + imageFileNames[0] , dataDirectory + imageFileNames[1] }; String[] imageZipPaths = { dataDirectory + imageFileNames[0] + ".zip" , dataDirectory + imageFileNames[1] + ".zip" }; Console.WriteLine("圧縮 START!"); for (int i = 0; i < imagePaths.Length; i++) { String imagePath = imagePaths[i]; using (var inputStream = new FileStream(imagePath, FileMode.Open)) { using (ZipFile zip = new ZipFile()) { zip.Password = imageZipPassword; zip.UpdateEntry(imageFileNames[i], inputStream); zip.Save(imageZipPaths[i]); } } } Console.WriteLine("圧縮 END!"); Console.WriteLine("解凍圧縮 START!"); try { using (ZipOutputStream output = new ZipOutputStream(dataDirectory + "ftp.zip")) { output.Password = "******"; for (int i = 0; i < imageZipPaths.Length; i++) { using (ZipFile zip = ZipFile.Read(new FileStream(imageZipPaths[i], FileMode.Open))) { zip.Password = imageZipPassword; foreach (ZipEntry inputEntry in zip) { ZipEntry outputEntry = output.PutNextEntry(inputEntry.FileName); inputEntry.Extract(output); } } } } // 画像ZIPファイル削除 for (int i = 0; i < imageZipPaths.Length; i++) { File.Delete(imageZipPaths[i]); } } catch (BadPasswordException) { File.Delete(dataDirectory + "ftp.zip"); Console.WriteLine("解凍圧縮 ERROR (BadPassword)!"); return; } Console.WriteLine("解凍圧縮 END!"); }
/// <summary> /// Zips the specified directory files to a zip file. /// </summary> /// <param name="zipFilename">The filename and path of the zip file to create.</param> /// <param name="zipDirectorPath">The directory of the files to zip.</param> /// <param name="pattern">The directory search pattern.</param> /// <param name="searchOption">The directory search option.</param> /// <param name="extensionRegularExpression">The regular expression for excluding files from being compressed.</param> /// <param name="filesToInclude">The list of files that are only to be compressed.</param> /// <param name="encryptionPasswordPhrase">The password phrase used to encrypt the compression file.</param> /// <remarks>Extension Regular Expression should be in the form 'jpg|JPG|gif|GIF|doc|DOC|pdf|PDF'</remarks> public static void Compress(string zipFilename, string zipDirectorPath, string pattern, SearchOption searchOption, string extensionRegularExpression, List <string> filesToInclude, string encryptionPasswordPhrase) { // Get the collection of files in the directory string[] files = Directory.GetFiles(zipDirectorPath.TrimEnd('\\') + "\\", pattern, searchOption); // Create a new zip output stream using (ZipOutputStream stream = new ZipOutputStream(File.Create(zipFilename))) { // If the zip file should be encryped. if (!String.IsNullOrEmpty(encryptionPasswordPhrase)) { stream.Password = encryptionPasswordPhrase; } // 0 - store only to 9 - means best compression stream.SetLevel(9); // Create a memory buffer byte[] buffer = new byte[4096]; // For each file found foreach (string file in files) { bool excludeFile = false; // If a regular expression has been supplied. if (!String.IsNullOrEmpty(extensionRegularExpression)) { excludeFile = Regex.IsMatch(file.Trim(), @".*\.(" + extensionRegularExpression + @")$"); } // Find all files that need to be included. if (filesToInclude != null && !excludeFile) { // Should the current file be included. IEnumerable <string> includeFiles = filesToInclude.Where(u => u.ToLower() == file.ToLower()); if (includeFiles.Count() > 0) { excludeFile = false; } else { excludeFile = true; } } // If file should not be excluded if (!excludeFile) { // Get the relative info string relativePath = Path.GetDirectoryName(file).TrimEnd('\\') + "\\"; relativePath = relativePath.Replace(zipDirectorPath.TrimEnd('\\') + "\\", "").Replace("\\", "/"); // Using GetFileName makes the result compatible // as the resulting path is not absolute. ZipEntry entry = new ZipEntry((!String.IsNullOrEmpty(relativePath) ? relativePath.TrimEnd('/') + "/" : "") + Path.GetFileName(file)); // Assign the zip entry attributes entry.DateTime = DateTime.Now; stream.PutNextEntry(entry); // Create a new file stream to read the // contens of the file using (FileStream fileStream = File.OpenRead(file)) { // Using a fixed size buffer here makes no noticeable difference for output // but keeps a lid on memory usage. int sourceBytes; do { // Read the file and erite to the zip file. sourceBytes = fileStream.Read(buffer, 0, buffer.Length); stream.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } } } // Finish is important to ensure trailing information for a Zip file is appended. // Without this the created file would be invalid. stream.Finish(); // Close is important to wrap things up and unlock the file. stream.Close(); } }
public void BaseClosedAfterFailure() { var ms = new MemoryStreamEx(new byte[32]); Assert.IsFalse(ms.IsClosed, "Underlying stream should NOT be closed initially"); var blewUp = false; try { using (var stream = new ZipOutputStream(ms)) { Assert.IsTrue(stream.IsStreamOwner, "Should be stream owner by default"); try { stream.PutNextEntry(new ZipEntry("Tiny")); stream.Write(new byte[32], 0, 32); } finally { Assert.IsFalse(ms.IsClosed, "Stream should still not be closed."); stream.Close(); Assert.Fail("Exception not thrown"); } } } catch { blewUp = true; } Assert.IsTrue(blewUp, "Should have failed to write to stream"); Assert.IsTrue(ms.IsClosed, "Underlying stream should be closed"); }
protected void MakeZipFile(Stream storage, bool isOwner, string entryNamePrefix, int entries, int size, string comment) { using (var zOut = new ZipOutputStream(storage)) { zOut.IsStreamOwner = isOwner; zOut.SetComment(comment); for (var i = 0; i < entries; ++i) { zOut.PutNextEntry(new ZipEntry(entryNamePrefix + (i + 1))); AddKnownDataToEntry(zOut, size); } } }
protected void MakeZipFile(string name, string entryNamePrefix, int entries, int size, string comment) { using (var fs = File.Create(name)) { using (var zOut = new ZipOutputStream(fs)) { zOut.SetComment(comment); for (var i = 0; i < entries; ++i) { zOut.PutNextEntry(new ZipEntry(entryNamePrefix + (i + 1))); AddKnownDataToEntry(zOut, size); } } } }
protected void MakeZipFile(string name, string[] names, int size, string comment) { using (var fs = File.Create(name)) { using (var zOut = new ZipOutputStream(fs)) { zOut.SetComment(comment); for (var i = 0; i < names.Length; ++i) { zOut.PutNextEntry(new ZipEntry(names[i])); AddKnownDataToEntry(zOut, size); } zOut.Close(); } fs.Close(); } }
protected void MakeZipFile(Stream storage, bool isOwner, string[] names, int size, string comment) { using (var zOut = new ZipOutputStream(storage)) { zOut.IsStreamOwner = isOwner; zOut.SetComment(comment); for (var i = 0; i < names.Length; ++i) { zOut.PutNextEntry(new ZipEntry(names[i])); AddKnownDataToEntry(zOut, size); } zOut.Close(); } }
public void ExtractEmptyDirectories() { var tempFilePath = GetTempFilePath(); Assert.IsNotNull(tempFilePath, "No permission to execute this test?"); var name = Path.Combine(tempFilePath, "x.zip"); EnsureTestDirectoryIsEmpty(tempFilePath); var targetDir = Path.Combine(tempFilePath, ZipTempDir + @"\floyd"); using (var fs = File.Create(name)) { using (var zOut = new ZipOutputStream(fs)) { zOut.PutNextEntry(new ZipEntry("floyd/")); } } var fastZip = new FastZip(); fastZip.CreateEmptyDirectories = true; fastZip.ExtractZip(name, targetDir, "zz"); File.Delete(name); Assert.IsTrue(Directory.Exists(targetDir), "Empty directory should be created"); }
protected byte[] MakeInMemoryZip(ref byte[] original, CompressionMethod method, int compressionLevel, int size, string password, bool withSeek) { MemoryStream ms; if (withSeek) { ms = new MemoryStream(); } else { ms = new MemoryStreamWithoutSeek(); } using (var outStream = new ZipOutputStream(ms)) { outStream.Password = password; if (method != CompressionMethod.Stored) { outStream.SetLevel(compressionLevel); // 0 - store only to 9 - means best compression } var entry = new ZipEntry("dummyfile.tst"); entry.CompressionMethod = method; outStream.PutNextEntry(entry); if (size > 0) { var rnd = new Random(); original = new byte[size]; rnd.NextBytes(original); outStream.Write(original, 0, original.Length); } } return ms.ToArray(); }
/// <summary> /// 生成压缩文件 /// </summary> /// <param name="strZipPath">生成的zip文件的路径</param> /// <param name="strZipTopDirectoryPath">源文件的上级目录</param> /// <param name="intZipLevel">T压缩等级</param> /// <param name="strPassword">压缩包解压密码</param> /// <param name="filesOrDirectoriesPaths">源文件路径</param> /// <returns></returns> public static bool Zip(string strZipPath, string strZipTopDirectoryPath, int intZipLevel, string strPassword, string[] filesOrDirectoriesPaths) { try { List <string> AllFilesPath = new List <string>(); if (filesOrDirectoriesPaths.Length > 0) // get all files path { for (int i = 0; i < filesOrDirectoriesPaths.Length; i++) { if (File.Exists(filesOrDirectoriesPaths[i])) { AllFilesPath.Add(filesOrDirectoriesPaths[i]); } else if (Directory.Exists(filesOrDirectoriesPaths[i])) { GetDirectoryFiles(filesOrDirectoriesPaths[i], AllFilesPath); } } } if (AllFilesPath.Count > 0) { ZipOutputStream zipOutputStream = new ZipOutputStream(File.Create(strZipPath)); zipOutputStream.SetLevel(intZipLevel); zipOutputStream.Password = strPassword; for (int i = 0; i < AllFilesPath.Count; i++) { string strFile = AllFilesPath[i].ToString(); try { if (strFile.Substring(strFile.Length - 1) == "") //folder { string strFileName = strFile.Replace(strZipTopDirectoryPath, ""); if (strFileName.StartsWith("")) { strFileName = strFileName.Substring(1); } ZipEntry entry = new ZipEntry(strFileName); entry.DateTime = DateTime.Now; zipOutputStream.PutNextEntry(entry); } else //file { FileStream fs = File.OpenRead(strFile); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); string strFileName = strFile.Replace(strZipTopDirectoryPath, ""); if (strFileName.StartsWith("")) { strFileName = strFileName.Substring(0); } ZipEntry entry = new ZipEntry(strFileName); entry.DateTime = DateTime.Now; zipOutputStream.PutNextEntry(entry); zipOutputStream.Write(buffer, 0, buffer.Length); fs.Close(); fs.Dispose(); } } catch { continue; } } zipOutputStream.Finish(); zipOutputStream.Close(); return(true); } else { return(false); } } catch { return(false); } }
// These two data types are supported in DotNetZip, but only if .NET Framework is targeted. //private SelfExtractorFlavor _selfExtractorFlavor; //private SelfExtractorSaveOptions _selfExtractorSaveOptions; public void CallAll() { // These two apis are supported in DotNetZip, but only if .NET Framework is targeted. //_zipFile.SaveSelfExtractor(_string, _selfExtractorFlavor); //_zipFile.SaveSelfExtractor(_string, _selfExtractorSaveOptions); //Project: Ionic.Zip _bZip2InputStream.Close(); _bZip2InputStream.Flush(); _int = _bZip2InputStream.Read(_bytes, _int, _int); _int = _bZip2InputStream.ReadByte(); _long = _bZip2InputStream.Seek(_long, _seekOrigin); _bZip2InputStream.SetLength(_long); _bZip2InputStream.Write(_bytes, _int, _int); _bZip2OutputStream.Close(); _bZip2OutputStream.Flush(); _int = _bZip2OutputStream.Read(_bytes, _int, _int); _long = _bZip2OutputStream.Seek(_long, _seekOrigin); _bZip2OutputStream.SetLength(_long); _bZip2OutputStream.Write(_bytes, _int, _int); _parallelBZip2OutputStream.Close(); _parallelBZip2OutputStream.Flush(); _int = _parallelBZip2OutputStream.Read(_bytes, _int, _int); _long = _parallelBZip2OutputStream.Seek(_long, _seekOrigin); _parallelBZip2OutputStream.SetLength(_long); _parallelBZip2OutputStream.Write(_bytes, _int, _int); _crc32.Combine(_int, _int); _int = _crc32.ComputeCrc32(_int, _byte); _int = _crc32.GetCrc32(_stream); _int = _crc32.GetCrc32AndCopy(_stream, _stream); _crc32.Reset(); _crc32.SlurpBlock(_bytes, _int, _int); _crc32.UpdateCRC(_byte); _crc32.UpdateCRC(_byte, _int); _crcCalculatorStream.Close(); _crcCalculatorStream.Flush(); _int = _crcCalculatorStream.Read(_bytes, _int, _int); _long = _crcCalculatorStream.Seek(_long, _seekOrigin); _crcCalculatorStream.SetLength(_long); _crcCalculatorStream.Write(_bytes, _int, _int); _zipEntriesCollection = _fileSelector.SelectEntries(_zipFile); _zipEntriesCollection = _fileSelector.SelectEntries(_zipFile, _string); _stringsCollection = _fileSelector.SelectFiles(_string); _stringsReadOnly = _fileSelector.SelectFiles(_string, _bool); _string = _fileSelector.ToString(); _bool = _comHelper.CheckZip(_string); _bool = _comHelper.CheckZipPassword(_string, _string); _comHelper.FixZipDirectory(_string); _string = _comHelper.GetZipLibraryVersion(); _bool = _comHelper.IsZipFile(_string); _bool = _comHelper.IsZipFileWithExtract(_string); _countingStream.Adjust(_long); _countingStream.Flush(); _int = _countingStream.Read(_bytes, _int, _int); _long = _countingStream.Seek(_long, _seekOrigin); _countingStream.SetLength(_long); _countingStream.Write(_bytes, _int, _int); _zipEntry.Extract(); _zipEntry.Extract(_extractExistingFileAction); _zipEntry.Extract(_string); _zipEntry.Extract(_string, _extractExistingFileAction); _zipEntry.Extract(_stream); _zipEntry.ExtractWithPassword(_extractExistingFileAction, _string); _zipEntry.ExtractWithPassword(_string); _zipEntry.ExtractWithPassword(_string, _extractExistingFileAction, _string); _zipEntry.ExtractWithPassword(_string, _string); _zipEntry.ExtractWithPassword(_stream, _string); _crcCalculatorStream = _zipEntry.OpenReader(); _crcCalculatorStream = _zipEntry.OpenReader(_string); _zipEntry.SetEntryTimes(_datetime, _datetime, _datetime); _string = _zipEntry.ToString(); _zipEntry = _zipFile.AddDirectory(_string); _zipEntry = _zipFile.AddDirectory(_string, _string); _zipEntry = _zipFile.AddDirectoryByName(_string); _zipEntry = _zipFile.AddEntry(_string, _bytes); _zipEntry = _zipFile.AddEntry(_string, _openDelegate, _closeDelegate); _zipEntry = _zipFile.AddEntry(_string, _writeDelegate); _zipEntry = _zipFile.AddEntry(_string, _string); _zipEntry = _zipFile.AddEntry(_string, _string, _encoding); _zipEntry = _zipFile.AddEntry(_string, _stream); _zipEntry = _zipFile.AddFile(_string); _zipEntry = _zipFile.AddFile(_string, _string); _zipFile.AddFiles(_strings); _zipFile.AddFiles(_strings, _bool, _string); _zipFile.AddFiles(_strings, _string); _zipEntry = _zipFile.AddItem(_string); _zipEntry = _zipFile.AddItem(_string, _string); _zipFile.AddSelectedFiles(_string); _zipFile.AddSelectedFiles(_string, _bool); _zipFile.AddSelectedFiles(_string, _string); _zipFile.AddSelectedFiles(_string, _string, _bool); _zipFile.AddSelectedFiles(_string, _string, _string); _zipFile.AddSelectedFiles(_string, _string, _string, _bool); _bool = _zipFile.ContainsEntry(_string); _zipFile.Dispose(); _zipFile.ExtractAll(_string); _zipFile.ExtractAll(_string, _extractExistingFileAction); _zipFile.ExtractSelectedEntries(_string); _zipFile.ExtractSelectedEntries(_string, _extractExistingFileAction); _zipFile.ExtractSelectedEntries(_string, _string); _zipFile.ExtractSelectedEntries(_string, _string, _string); _zipFile.ExtractSelectedEntries(_string, _string, _string, _extractExistingFileAction); _enumerator = _zipFile.GetNewEnum(); _zipFile.Initialize(_string); _zipFile.RemoveEntries(_zipEntriesCollection); _zipFile.RemoveEntries(_stringsCollection); _zipFile.RemoveEntry(_zipEntry); _zipFile.RemoveEntry(_string); _int = _zipFile.RemoveSelectedEntries(_string); _int = _zipFile.RemoveSelectedEntries(_string, _string); _zipFile.Save(); _zipFile.Save(_string); _zipFile.Save(_stream); _zipEntriesCollection = _zipFile.SelectEntries(_string); _zipEntriesCollection = _zipFile.SelectEntries(_string, _string); _string = _zipFile.ToString(); _zipEntry = _zipFile.UpdateDirectory(_string); _zipEntry = _zipFile.UpdateDirectory(_string, _string); _zipEntry = _zipFile.UpdateEntry(_string, _bytes); _zipEntry = _zipFile.UpdateEntry(_string, _openDelegate, _closeDelegate); _zipEntry = _zipFile.UpdateEntry(_string, _writeDelegate); _zipEntry = _zipFile.UpdateEntry(_string, _string); _zipEntry = _zipFile.UpdateEntry(_string, _string, _encoding); _zipEntry = _zipFile.UpdateEntry(_string, _stream); _zipEntry = _zipFile.UpdateFile(_string); _zipFile.UpdateFile(_string, _string); _zipFile.UpdateFiles(_strings); _zipFile.UpdateFiles(_strings, _string); _zipFile.UpdateItem(_string); _zipFile.UpdateItem(_string, _string); _zipFile.UpdateSelectedFiles(_string, _string, _string, _bool); _zipInputStream.Flush(); _zipEntry = _zipInputStream.GetNextEntry(); _int = _zipInputStream.Read(_bytes, _int, _int); _long = _zipInputStream.Seek(_long, _seekOrigin); _zipInputStream.SetLength(_long); _string = _zipInputStream.ToString(); _zipInputStream.Write(_bytes, _int, _int); _bool = _zipOutputStream.ContainsEntry(_string); _zipOutputStream.Flush(); _zipEntry = _zipOutputStream.PutNextEntry(_string); _int = _zipOutputStream.Read(_bytes, _int, _int); _long = _zipOutputStream.Seek(_long, _seekOrigin); _zipOutputStream.SetLength(_long); _string = _zipOutputStream.ToString(); _zipOutputStream.Write(_bytes, _int, _int); _deflateStream.Flush(); _int = _deflateStream.Read(_bytes, _int, _int); _long = _deflateStream.Seek(_long, _seekOrigin); _deflateStream.SetLength(_long); _deflateStream.Write(_bytes, _int, _int); _gZipStream.Flush(); _int = _gZipStream.Read(_bytes, _int, _int); _long = _gZipStream.Seek(_long, _seekOrigin); _gZipStream.SetLength(_long); _gZipStream.Write(_bytes, _int, _int); _parallelDeflateOutputStream.Close(); _parallelDeflateOutputStream.Flush(); _int = _parallelDeflateOutputStream.Read(_bytes, _int, _int); _parallelDeflateOutputStream.Reset(_stream); _long = _parallelDeflateOutputStream.Seek(_long, _seekOrigin); _parallelDeflateOutputStream.SetLength(_long); _parallelDeflateOutputStream.Write(_bytes, _int, _int); // Static _bool = ZipFile.CheckZip(_string); _bool = ZipFile.CheckZip(_string, _bool, _textWriter); _bool = ZipFile.CheckZipPassword(_string, _string); ZipFile.FixZipDirectory(_string); _bool = ZipFile.IsZipFile(_string); _bool = ZipFile.IsZipFile(_string, _bool); _bool = ZipFile.IsZipFile(_stream, _bool); _zipFile = ZipFile.Read(_string); _zipFile = ZipFile.Read(_string, _readOptions); _zipFile = ZipFile.Read(_stream); _zipFile = ZipFile.Read(_stream, _readOptions); _uint = Adler.Adler32(_uint, _bytes, _int, _int); _bytes = DeflateStream.CompressBuffer(_bytes); _bytes = DeflateStream.CompressString(_string); _bytes = DeflateStream.UncompressBuffer(_bytes); _string = DeflateStream.UncompressString(_bytes); _bytes = GZipStream.CompressBuffer(_bytes); _bytes = GZipStream.CompressString(_string); _bytes = GZipStream.UncompressBuffer(_bytes); _string = GZipStream.UncompressString(_bytes); _bytes = ZlibStream.CompressBuffer(_bytes); _bytes = ZlibStream.CompressString(_string); _bytes = ZlibStream.UncompressBuffer(_bytes); _string = ZlibStream.UncompressString(_bytes); }
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"); }
private static void WriteFileToZip(ZipOutputStream stream, string filename, byte[] bytes) { stream.PutNextEntry(new ZipEntry(filename)); stream.Write(bytes, 0, bytes.Length); }
public void EntryWithNoDataAndZip64() { MemoryStream msw = new MemoryStreamWithoutSeek(); var outStream = new ZipOutputStream(msw); outStream.IsStreamOwner = false; var ze = new ZipEntry("Striped Marlin"); ze.ForceZip64(); ze.Size = 0; outStream.PutNextEntry(ze); outStream.CloseEntry(); outStream.Finish(); outStream.Close(); var ms = new MemoryStream(msw.ToArray()); using (var zf = new ZipFile(ms)) { Assert.IsTrue(zf.TestArchive(true)); } }
private void m_Worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { ExportData data = (ExportData)e.Argument; long overallSize = 0; // collect entries and calculate overall size Dictionary <ZipEntry, String> zipEntries = new Dictionary <ZipEntry, string>(); Dictionary <ZipEntry, long> zipSizes = new Dictionary <ZipEntry, long>(); // project file: no path ZipEntry entry = new ZipEntry(System.IO.Path.GetFileName(data.InnerFileName)); long size; SetZipEntryAttributes(entry, data.InnerFileName, out size); zipEntries[entry] = data.InnerFileName; zipSizes[entry] = size; overallSize += size; List <String> musicFiles = new List <string>(); // entries for the music and sound files Ares.ModelInfo.FileLists fileLists = new Ares.ModelInfo.FileLists(); foreach (IFileElement element in fileLists.GetAllFiles(data.Data)) { String name = element.SoundFileType == SoundFileType.Music ? MUSIC_DIR : SOUND_DIR; name = System.IO.Path.Combine(name, element.FilePath); String fileName = element.SoundFileType == SoundFileType.Music ? Settings.Settings.Instance.MusicDirectory : Settings.Settings.Instance.SoundDirectory; fileName = System.IO.Path.Combine(fileName, element.FilePath); ZipEntry fileEntry = new ZipEntry(ZipEntry.CleanName(name)); SetZipEntryAttributes(fileEntry, fileName, out size); zipEntries[fileEntry] = fileName; zipSizes[fileEntry] = size; overallSize += size; if (element.FilePath.EndsWith(".m3u", StringComparison.InvariantCultureIgnoreCase) || element.FilePath.EndsWith(".m3u8", StringComparison.InvariantCultureIgnoreCase) || element.FilePath.EndsWith(".pls", StringComparison.InvariantCultureIgnoreCase)) { List <String> filesInPlaylist = Playlists.ReadPlaylist(fileName, (String error) => { throw new System.IO.IOException(error); }); if (filesInPlaylist != null) { String pathStart = element.SoundFileType == SoundFileType.Music ? Settings.Settings.Instance.MusicDirectory : Settings.Settings.Instance.SoundDirectory; foreach (String playlistFile in filesInPlaylist) { if (playlistFile.StartsWith(pathStart, StringComparison.InvariantCultureIgnoreCase)) { name = element.SoundFileType == SoundFileType.Music ? MUSIC_DIR : SOUND_DIR; name = System.IO.Path.Combine(name, playlistFile.Substring(pathStart.Length + 1)); if (element.SoundFileType == SoundFileType.Music) { musicFiles.Add(playlistFile.Substring(pathStart.Length + 1)); } ZipEntry playlistFileEntry = new ZipEntry(ZipEntry.CleanName(name)); SetZipEntryAttributes(playlistFileEntry, playlistFile, out size); zipEntries[playlistFileEntry] = playlistFile; zipSizes[playlistFileEntry] = size; overallSize += size; } } } } else if (element.SoundFileType == SoundFileType.Music) { musicFiles.Add(element.FilePath); } } // export tags database String tagFileName = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "aresmusictags.jsv"); Ares.Tags.TagsModule.GetTagsDB().FilesInterface.ExportDatabase(musicFiles, tagFileName); String tagFileEntryName = System.IO.Path.Combine(MUSIC_DIR, "aresmusictags.jsv"); ZipEntry tagFileEntry = new ZipEntry(ZipEntry.CleanName(tagFileEntryName)); SetZipEntryAttributes(tagFileEntry, tagFileName, out size); zipEntries[tagFileEntry] = tagFileName; zipSizes[tagFileEntry] = size; overallSize += size; // now write zip file long writtenSize = 0; int lastPercent = -1; String lastFile = String.Empty; using (ZipOutputStream stream = new ZipOutputStream(System.IO.File.Create(data.ExportFileName))) { stream.SetLevel(7); byte[] buffer = new byte[4096]; foreach (KeyValuePair <ZipEntry, String> zipEntry in zipEntries) { stream.PutNextEntry(zipEntry.Key); using (System.IO.FileStream fileStream = System.IO.File.OpenRead(zipEntry.Value)) { StreamUtils.Copy(fileStream, stream, buffer, new ProgressHandler((object o, ProgressEventArgs e2) => { long currentSize = writtenSize + e2.Processed; int currentPercent = (int)(((double)currentSize / (double)overallSize) * 100.0); if (currentPercent != lastPercent || e2.Name != lastFile) { lastPercent = currentPercent; lastFile = e2.Name; m_Worker.ReportProgress(currentPercent, lastFile); e2.ContinueRunning = !m_Worker.CancellationPending; } }), TimeSpan.FromMilliseconds(50), zipEntry.Key, zipEntry.Value, zipEntry.Key.Size); } writtenSize += zipSizes[zipEntry.Key]; if (m_Worker.CancellationPending) { e.Cancel = true; break; } } stream.Finish(); stream.Close(); } }
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"); }
private void writeKML(string filename) { try { writeGPX(filename); } catch { } Color[] colours = { Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Blue, Color.Indigo, Color.Violet, Color.Pink }; AltitudeMode altmode = AltitudeMode.absolute; // all new logs have both agl and asl, we are using asl. this may break old logs // if (MainV2.comPort.MAV.cs.firmware == MainV2.Firmwares.ArduCopter2) { // altmode = AltitudeMode.relativeToGround; // because of sonar, this is both right and wrong. right for sonar, wrong in terms of gps as the land slopes off. } KMLRoot kml = new KMLRoot(); Folder fldr = new Folder("Log"); Style style = new Style(); style.Id = "yellowLineGreenPoly"; style.Add(new LineStyle(HexStringToColor("7f00ffff"), 4)); PolyStyle pstyle = new PolyStyle(); pstyle.Color = HexStringToColor("7f00ff00"); style.Add(pstyle); kml.Document.AddStyle(style); int stylecode = 0xff; int g = -1; foreach (List <Point3D> poslist in position) { g++; if (poslist == null) { continue; } LineString ls = new LineString(); ls.AltitudeMode = altmode; ls.Extrude = true; //ls.Tessellate = true; Coordinates coords = new Coordinates(); coords.AddRange(poslist); ls.coordinates = coords; Placemark pm = new Placemark(); string mode = ""; if (g < modelist.Count) { mode = modelist[g]; } pm.name = g + " Flight Path " + mode; pm.styleUrl = "#yellowLineGreenPoly"; pm.LineString = ls; stylecode = colours[g % (colours.Length - 1)].ToArgb(); Style style2 = new Style(); Color color = Color.FromArgb(0xff, (stylecode >> 16) & 0xff, (stylecode >> 8) & 0xff, (stylecode >> 0) & 0xff); log.Info("colour " + color.ToArgb().ToString("X") + " " + color.ToKnownColor().ToString()); style2.Add(new LineStyle(color, 4)); pm.AddStyle(style2); fldr.Add(pm); } Folder planes = new Folder(); planes.name = "Planes"; fldr.Add(planes); Folder waypoints = new Folder(); waypoints.name = "Waypoints"; fldr.Add(waypoints); LineString lswp = new LineString(); lswp.AltitudeMode = AltitudeMode.relativeToGround; lswp.Extrude = true; Coordinates coordswp = new Coordinates(); foreach (PointLatLngAlt p1 in cmd) { coordswp.Add(new Point3D(p1.Lng, p1.Lat, p1.Alt)); } lswp.coordinates = coordswp; Placemark pmwp = new Placemark(); pmwp.name = "Waypoints"; //pm.styleUrl = "#yellowLineGreenPoly"; pmwp.LineString = lswp; waypoints.Add(pmwp); int a = 0; int l = -1; Model lastmodel = null; foreach (Data mod in flightdata) { l++; if (mod.model.Location.latitude == 0) { continue; } if (lastmodel != null) { if (lastmodel.Location.Equals(mod.model.Location)) { continue; } } Placemark pmplane = new Placemark(); pmplane.name = "Plane " + a; pmplane.visibility = false; Model model = mod.model; model.AltitudeMode = altmode; model.Scale.x = 2; model.Scale.y = 2; model.Scale.z = 2; try { pmplane.description = @"<![CDATA[ <table> <tr><td>Roll: " + model.Orientation.roll + @" </td></tr> <tr><td>Pitch: " + model.Orientation.tilt + @" </td></tr> <tr><td>Yaw: " + model.Orientation.heading + @" </td></tr> <tr><td>WP dist " + mod.ntun[2] + @" </td></tr> <tr><td>tar bear " + mod.ntun[3] + @" </td></tr> <tr><td>nav bear " + mod.ntun[4] + @" </td></tr> <tr><td>alt error " + mod.ntun[5] + @" </td></tr> </table> ]]>"; } catch { } try { pmplane.Point = new KmlPoint((float)model.Location.longitude, (float)model.Location.latitude, (float)model.Location.altitude); pmplane.Point.AltitudeMode = altmode; Link link = new Link(); link.href = "block_plane_0.dae"; model.Link = link; pmplane.Model = model; planes.Add(pmplane); } catch { } // bad lat long value lastmodel = mod.model; a++; } kml.Document.Add(fldr); kml.Save(filename); // create kmz - aka zip file FileStream fs = File.Open(filename.Replace(".log.kml", ".kmz"), FileMode.Create); ZipOutputStream zipStream = new ZipOutputStream(fs); zipStream.SetLevel(9); //0-9, 9 being the highest level of compression zipStream.UseZip64 = UseZip64.Off; // older zipfile // entry 1 string entryName = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction ZipEntry newEntry = new ZipEntry(entryName); newEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(newEntry); // Zip the file in buffered chunks // the "using" will close the stream even if an exception occurs byte[] buffer = new byte[4096]; using (FileStream streamReader = File.OpenRead(filename)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); File.Delete(filename); filename = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + "block_plane_0.dae"; // entry 2 entryName = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction newEntry = new ZipEntry(entryName); newEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(newEntry); // Zip the file in buffered chunks // the "using" will close the stream even if an exception occurs buffer = new byte[4096]; using (FileStream streamReader = File.OpenRead(filename)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); zipStream.IsStreamOwner = true; // Makes the Close also Close the underlying stream zipStream.Close(); positionindex = 0; modelist.Clear(); flightdata.Clear(); position = new List <Core.Geometry.Point3D> [200]; cmd.Clear(); }
public void WriteThroughput() { outStream_ = new ZipOutputStream(new NullStream()); var startTime = DateTime.Now; long target = 0x10000000; writeTarget_ = target; outStream_.PutNextEntry(new ZipEntry("0")); WriteTargetBytes(); outStream_.Close(); var endTime = DateTime.Now; var span = endTime - startTime; Console.WriteLine("Time {0} throughput {1} KB/Sec", span, (target/1024)/span.TotalSeconds); }
///<summary> ///压缩文件 ///</summary> ///<param name="FileToZip">要进行压缩的文件名</param> ///<param name="ZipedFile">压缩后生成的压缩文件名,如果为空则文件名为待压缩的文件名加上.rar</param> ///<returns>压缩是否成功</returns> private static bool ZipFile(string FileToZip, string ZipedFile, string Password) { //如果文件没有找到,则报错 if (!File.Exists(FileToZip)) { throw new System.IO.FileNotFoundException("指定要压缩的文件: " + FileToZip + " 不存在!"); } if (ZipedFile == string.Empty) { //如果为空则文件名为待压缩的文件名加上.rar ZipedFile = FileToZip + ".zip"; } FileStream ZipFile = null; ZipOutputStream ZipStream = null; ZipEntry ZipEntry = null; bool res = true; ZipFile = File.Create(ZipedFile); ZipStream = new ZipOutputStream(ZipFile); ZipEntry = new ZipEntry(Path.GetFileName(FileToZip)); ZipStream.PutNextEntry(ZipEntry); ZipStream.SetLevel(6); if (!string.IsNullOrEmpty(Password.Trim())) { ZipStream.Password = Password.Trim(); } try { ZipFile = File.OpenRead(FileToZip); byte[] buffer = new byte[avg]; for (int i = 0; i < ZipFile.Length; i += avg) { if (i + avg > ZipFile.Length) { //不足100MB的部分写剩余部分 buffer = new byte[ZipFile.Length - i]; } ZipFile.Read(buffer, 0, buffer.Length); ZipStream.Write(buffer, 0, buffer.Length); } } catch (Exception ex) { res = false; } finally { if (ZipEntry != null) { ZipEntry = null; } if (ZipStream != null) { ZipStream.Finish(); ZipStream.Close(); } if (ZipFile != null) { ZipFile.Close(); ZipFile = null; } GC.Collect(); GC.Collect(1); } return(res); }
public void Zip64Descriptor() { MemoryStream msw = new MemoryStreamWithoutSeek(); var outStream = new ZipOutputStream(msw); outStream.UseZip64 = UseZip64.Off; outStream.IsStreamOwner = false; outStream.PutNextEntry(new ZipEntry("StripedMarlin")); outStream.WriteByte(89); outStream.Close(); var ms = new MemoryStream(msw.ToArray()); using (var zf = new ZipFile(ms)) { Assert.IsTrue(zf.TestArchive(true)); } msw = new MemoryStreamWithoutSeek(); outStream = new ZipOutputStream(msw); outStream.UseZip64 = UseZip64.On; outStream.IsStreamOwner = false; outStream.PutNextEntry(new ZipEntry("StripedMarlin")); outStream.WriteByte(89); outStream.Close(); ms = new MemoryStream(msw.ToArray()); using (var zf = new ZipFile(ms)) { Assert.IsTrue(zf.TestArchive(true)); } }
private void _buttonBrowser_Click(object sender, EventArgs e) { using (OpenFileDialog openFileDialog = new OpenFileDialog()) { if (!string.IsNullOrEmpty(m_app.PathBrowserLastest)) { openFileDialog.InitialDirectory = m_app.PathBrowserLastest; } else { openFileDialog.InitialDirectory = m_app.PATH_DATA; } //openFileDialog.Filter = "Image files (*.png)|*.png|(*.jpg)|*.jpg|All files (*.*)|*.*"; openFileDialog.Filter = "PDF Files (*.pdf)|*.pdf|EBook Files (*.ebk)|*.ebk|All Files (*.*)|*.*"; openFileDialog.FilterIndex = 2; openFileDialog.RestoreDirectory = true; if (openFileDialog.ShowDialog() == DialogResult.OK) { string file = openFileDialog.FileName; m_app.PathBrowserLastest = Path.GetDirectoryName(file); //openImage(file); _labelFile.Text = file; _labelMessage.Text = ""; string docName = Path.GetFileName(file); docName = m_app.doc_formatName(docName); var dic = new Dictionary <int, byte[]>(); string zipFile = Path.Combine(m_app.PATH_DATA, docName + ".ebk"); if (File.Exists(zipFile)) { dic = m_app.ebk_Read(zipFile); m_main.doc_Open(dic); this.Close(); return; } _buttonBrowser.Enabled = false; _buttonOpen.Enabled = false; _buttonClose.Enabled = false; using (var document = PdfDocument.Load(file)) { int dpi = 150, max = document.PageCount, wi = Screen.PrimaryScreen.WorkingArea.Width, hi = Screen.PrimaryScreen.WorkingArea.Height; string time = DateTime.Now.ToString("yyMMdd.HHmmss"); int wp = 0, hp = 0, w = 0, h = 0; for (int i = 0; i < max; i++) { //if (i != 5 && i != 7) continue; wp = (int)document.PageSizes[i].Width; hp = (int)document.PageSizes[i].Height; if (wp > hp) { w = IMG_WIDTH_BIG; h = w * hp / wp; } else { w = IMG_WIDTH_NORMAL; h = w * hp / wp; } using (var image = document.Render(i, w, h, dpi, dpi, PdfRenderFlags.Annotations)) { _labelMessage.Text = "Processing page " + (i + 1).ToString() + "..."; //image.Save(stream, ImageFormat.Jpeg); using (MemoryStream ms = new MemoryStream()) { image.Save(ms, ImageFormat.Jpeg); var buf = ms.ToArray(); dic.Add(i, buf); } } }//end for _buttonBrowser.Enabled = true; _buttonOpen.Enabled = true; _buttonClose.Enabled = true; _labelMessage.Text = "Process complete: " + max + " pages"; //m_redis.Hash[docName].Clear(); //m_redis.Hash[docName].Set(dic); //m_redis.WaitComplete(m_redis.SendCommand(RedisCommand.BGSAVE)); using (var fs = File.Create(zipFile)) { using (var zipStream = new ZipOutputStream(fs)) { zipStream.CompressionLevel = Ionic.Zlib.CompressionLevel.Level9; zipStream.Password = m_app.FOLDER_DATA; foreach (var kv in dic) { zipStream.PutNextEntry(kv.Key.ToString() + ".jpg"); zipStream.Write(kv.Value, 0, kv.Value.Length); } } } //using (var fileStream = File.Create(zipFile)) //{ // using (ZipOutputStream zipStream = new ZipOutputStream(fileStream)) // { // zipStream.SetLevel(9); // 0 - store only to 9 - means best compression // zipStream.Password = m_app.FOLDER_DATA; // foreach (var kv in dic) // { // var entry = new ZipEntry(kv.Key.ToString() + ".jpg"); // entry.DateTime = DateTime.Now; // zipStream.PutNextEntry(entry); // zipStream.Write(kv.Value, 0, kv.Value.Length); // } // } //} m_app.DocumentFile = file; m_app.DocumentName = docName; m_main.doc_Open(dic); this.Close(); } } } }
public static void ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize) { if (!File.Exists(fileToZip)) { throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!"); } using (FileStream stream = File.Create(zipedFile)) { using (ZipOutputStream stream2 = new ZipOutputStream(stream)) { using (FileStream stream3 = new FileStream(fileToZip, FileMode.Open, FileAccess.Read)) { ZipEntry entry = new ZipEntry(fileToZip.Substring(fileToZip.LastIndexOf(@"\") + 1)); stream2.PutNextEntry(entry); stream2.SetLevel(compressionLevel); byte[] buffer = new byte[blockSize]; int count = 0; try { do { count = stream3.Read(buffer, 0, buffer.Length); stream2.Write(buffer, 0, count); } while (count > 0); } catch (Exception exception) { throw exception; } stream3.Close(); } stream2.Finish(); stream2.Close(); } stream.Close(); } }
private void SaveSharedStringHandler(ZipOutputStream stream, CompressionLevel compressionLevel, string fileName) { //Packaging.ZipPackagePart stringPart; //if (_package.Package.PartExists(SharedStringsUri)) //{ // stringPart=_package.Package.GetPart(SharedStringsUri); //} //else //{ // stringPart = _package.Package.CreatePart(SharedStringsUri, @"application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml", _package.Compression); //Part.CreateRelationship(UriHelper.GetRelativeUri(WorkbookUri, SharedStringsUri), Packaging.TargetMode.Internal, ExcelPackage.schemaRelationships + "/sharedStrings"); //} //StreamWriter sw = new StreamWriter(stringPart.GetStream(FileMode.Create, FileAccess.Write)); //Init Zip stream.CompressionLevel = (OfficeOpenXml.Packaging.Ionic.Zlib.CompressionLevel)compressionLevel; stream.PutNextEntry(fileName); var cache = new StringBuilder(); var sw = new StreamWriter(stream); cache.AppendFormat("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?><sst xmlns=\"http://schemas.openxmlformats.org/spreadsheetml/2006/main\" count=\"{0}\" uniqueCount=\"{0}\">", _sharedStrings.Count); foreach (string t in _sharedStrings.Keys) { SharedStringItem ssi = _sharedStrings[t]; if (ssi.isRichText) { cache.Append("<si>"); ConvertUtil.ExcelEncodeString(cache, t); cache.Append("</si>"); } else { if (t.Length>0 && (t[0] == ' ' || t[t.Length-1] == ' ' || t.Contains(" ") || t.Contains("\t"))) { cache.Append("<si><t xml:space=\"preserve\">"); } else { cache.Append("<si><t>"); } ConvertUtil.ExcelEncodeString(cache, ConvertUtil.ExcelEscapeString(t)); cache.Append("</t></si>"); } if (cache.Length > 0x600000) { sw.Write(cache.ToString()); cache = new StringBuilder(); } } cache.Append("</sst>"); sw.Write(cache.ToString()); sw.Flush(); Part.CreateRelationship(UriHelper.GetRelativeUri(WorkbookUri, SharedStringsUri), Packaging.TargetMode.Internal, ExcelPackage.schemaRelationships + "/sharedStrings"); }
private static void ZipSetp(string strDirectory, ZipOutputStream s, string parentPath) { if (strDirectory[strDirectory.Length - 1] != Path.DirectorySeparatorChar) { strDirectory = strDirectory + Path.DirectorySeparatorChar; } Crc32 crc = new Crc32(); string[] fileSystemEntries = Directory.GetFileSystemEntries(strDirectory); foreach (string str in fileSystemEntries) { if (Directory.Exists(str)) { string str2 = parentPath; str2 = str2 + str.Substring(str.LastIndexOf(@"\") + 1) + @"\"; ZipSetp(str, s, str2); } else { using (FileStream stream = File.OpenRead(str)) { byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); ZipEntry entry = new ZipEntry(parentPath + str.Substring(str.LastIndexOf(@"\") + 1)) { DateTime = DateTime.Now, Size = stream.Length }; stream.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); } } } }
void zip() { System.Uri dest = new System.Uri(uri_chooser.Uri); Crc32 crc = new Crc32(); string filedest = dest.LocalPath + "/" + filename.Text; Log.DebugFormat("Creating zip file {0}", filedest); ZipOutputStream s = new ZipOutputStream(File.Create(filedest)); if (scale_check.Active) { Log.DebugFormat("Scaling to {0}", scale_size.ValueAsInt); } ProgressDialog progress_dialog = new ProgressDialog(Catalog.GetString("Exporting files"), ProgressDialog.CancelButtonType.Stop, photos.Length, zipdiag); //Pack up for (int i = 0; i < photos.Length; i++) { if (progress_dialog.Update(string.Format(Catalog.GetString("Preparing photo \"{0}\""), photos[i].Name))) { progress_dialog.Destroy(); return; } string f = null; // FIXME: embed in a try/catch if (scale_check.Active) { FilterSet filters = new FilterSet(); filters.Add(new JpegFilter()); filters.Add(new ResizeFilter((uint)scale_size.ValueAsInt)); FilterRequest freq = new FilterRequest(photos [i].DefaultVersion.Uri); filters.Convert(freq); f = freq.Current.LocalPath; } else { f = photos [i].DefaultVersion.Uri.LocalPath; } FileStream fs = File.OpenRead(f); byte [] buffer = new byte [fs.Length]; fs.Read(buffer, 0, buffer.Length); ZipEntry entry = new ZipEntry(System.IO.Path.GetFileName(photos [i].DefaultVersion.Uri.LocalPath)); entry.DateTime = DateTime.Now; entry.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); } s.Finish(); s.Close(); if (progress_dialog != null) { progress_dialog.Destroy(); } }
public static void ZipFile(string fileToZip, string zipedFile) { if (!File.Exists(fileToZip)) { throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!"); } using (FileStream stream = File.OpenRead(fileToZip)) { byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); stream.Close(); using (FileStream stream2 = File.Create(zipedFile)) { using (ZipOutputStream stream3 = new ZipOutputStream(stream2)) { ZipEntry entry = new ZipEntry(fileToZip.Substring(fileToZip.LastIndexOf(@"\") + 1)); stream3.PutNextEntry(entry); stream3.SetLevel(5); stream3.Write(buffer, 0, buffer.Length); stream3.Finish(); stream3.Close(); } } } }
/// <summary> /// 压缩多个文件/文件夹 /// </summary> /// <param name="sourceList">源文件/文件夹路径列表</param> /// <param name="zipFilePath">压缩文件路径</param> /// <param name="comment">注释信息</param> /// <param name="password">压缩密码</param> /// <param name="compressionLevel">压缩等级,范围从0到9,可选,默认为6</param> /// <returns></returns> public static bool CompressFile(IEnumerable <string> sourceList, string zipFilePath, string comment = null, string password = null, int compressionLevel = 6) { bool result = false; try { //检测目标文件所属的文件夹是否存在,如果不存在则建立 string zipFileDirectory = Path.GetDirectoryName(zipFilePath); if (!Directory.Exists(zipFileDirectory)) { Directory.CreateDirectory(zipFileDirectory); } Dictionary <string, string> dictionaryList = PrepareFileSystementities(sourceList); using (ZipOutputStream zipStream = new ZipOutputStream(File.Create(zipFilePath))) { zipStream.Password = password; //设置密码 zipStream.SetComment(comment); //添加注释 zipStream.SetLevel(CheckCompressionLevel(compressionLevel)); //设置压缩等级 foreach (string key in dictionaryList.Keys) //从字典取文件添加到压缩文件 { if (File.Exists(key)) //判断是文件还是文件夹 { FileInfo fileItem = new FileInfo(key); using (FileStream readStream = fileItem.Open(FileMode.Open, FileAccess.Read, FileShare.Read)) { ZipEntry zipEntry = new ZipEntry(dictionaryList[key]) { DateTime = fileItem.LastWriteTime, Size = readStream.Length }; zipStream.PutNextEntry(zipEntry); int readLength = 0; byte[] buffer = new byte[BufferSize]; do { readLength = readStream.Read(buffer, 0, BufferSize); zipStream.Write(buffer, 0, readLength); } while (readLength == BufferSize); readStream.Close(); } } else//对文件夹的处理 { ZipEntry zipEntry = new ZipEntry(dictionaryList[key] + "/"); zipStream.PutNextEntry(zipEntry); } } zipStream.Flush(); zipStream.Finish(); zipStream.Close(); } result = true; } catch (System.Exception ex) { throw new Exception("压缩文件失败", ex); } return(result); }
public static void TestZippedStream(int len, int ziplevel) { DateTime t1, t2; TimeSpan dt; Foo o = new Foo(); o.Fill(len); System.IO.FileStream zipoutfile = System.IO.File.Create(@"C:\temp\xmlteststream01.xml.zip"); ZipOutputStream ZipStream = new ZipOutputStream(zipoutfile); ZipEntry ZipEntry = new ZipEntry("Table/Table1.xml"); ZipStream.PutNextEntry(ZipEntry); ZipStream.SetLevel(ziplevel); XmlStreamSerializationInfo info = new XmlStreamSerializationInfo(); t1 = DateTime.Now; info.BeginWriting(ZipStream); info.AddValue("FooNode",o); info.EndWriting(); ZipStream.Finish(); ZipStream.Close(); zipoutfile.Close(); t2 = DateTime.Now; dt = t2-t1; Console.WriteLine("Document saved, duration {0}.",dt); t1 = DateTime.Now; ZipFile zipfile = new ZipFile(@"C:\temp\xmlteststream01.xml.zip"); System.IO.Stream zipinpstream = zipfile.GetInputStream(new ZipEntry("Table/Table1.xml")); XmlStreamDeserializationInfo info3 = new XmlStreamDeserializationInfo(); info3.BeginReading(zipinpstream); Foo o3 = (Foo)info3.GetValue(null); info3.EndReading(); zipinpstream.Close(); zipfile.Close(); t2 = DateTime.Now; dt = t2-t1; Console.WriteLine("Document restored, duration {0}.",dt); o3.EnsureEquality(len); }
public void ZipBombCreateAndHandle() { // #50090 / #56865 ZipFile zipFile = ZipHelper.OpenZipFile(OpenXml4NetTestDataSamples.GetSampleFile("sample.xlsx")); Assert.IsNotNull(zipFile); ByteArrayOutputStream bos = new ByteArrayOutputStream(2500000); ZipOutputStream append = new ZipOutputStream(bos); // first, copy contents from existing war IEnumerator entries = zipFile.GetEnumerator(); while (entries.MoveNext()) { ZipEntry e2 = (ZipEntry)entries.Current; ZipEntry e = new ZipEntry(e2.Name); e.DateTime = (e2.DateTime); e.Comment = (e2.Comment); e.Size = (e2.Size); append.PutNextEntry(e); if (!e.IsDirectory) { Stream is1 = zipFile.GetInputStream(e); if (e.Name.Equals("[Content_Types].xml")) { ByteArrayOutputStream bos2 = new ByteArrayOutputStream(); IOUtils.Copy(is1, bos2); long size = bos2.Length - "</Types>".Length; append.Write(bos2.ToByteArray(), 0, (int)size); byte[] spam = new byte[0x7FFF]; for (int i = 0; i < spam.Length; i++) { spam[i] = (byte)' '; } // 0x7FFF0000 is the maximum for 32-bit zips, but less still works while (size < 0x7FFF0000) { append.Write(spam, 0, spam.Length); size += spam.Length; } append.Write(Encoding.ASCII.GetBytes("</Types>"), 0, 8); size += 8; e.Size = (size); } else { IOUtils.Copy(is1, append); } } append.CloseEntry(); } append.Close(); zipFile.Close(); byte[] buf = bos.ToByteArray(); bos = null; IWorkbook wb = WorkbookFactory.Create(new ByteArrayInputStream(buf)); wb.GetSheetAt(0); wb.Close(); zipFile.Close(); }
public static void TestZipped() { DateTime t1, t2; TimeSpan dt; Foo o = new Foo(); o.Fill(100000); t1 = DateTime.Now; XmlDocumentSerializationInfo info = new XmlDocumentSerializationInfo(); info.AddValue("FooNode",o); System.IO.FileStream zipoutfile = System.IO.File.Create(@"C:\temp\xmltest03.xml.zip"); ZipOutputStream ZipStream = new ZipOutputStream(zipoutfile); ZipEntry ZipEntry = new ZipEntry("Table/Table1.xml"); ZipStream.PutNextEntry(ZipEntry); ZipStream.SetLevel(7); info.Doc.Save(ZipStream); ZipStream.Finish(); ZipStream.Close(); zipoutfile.Close(); t2 = DateTime.Now; dt = t2-t1; Console.WriteLine("Document saved, duration {0}.",dt); t1 = DateTime.Now; ZipFile zipfile = new ZipFile(@"C:\temp\xmltest03.xml.zip"); System.IO.Stream zipinpstream = zipfile.GetInputStream(new ZipEntry("Table/Table1.xml")); XmlDocument doc3 = new XmlDocument(); doc3.Load(zipinpstream); XmlDocumentSerializationInfo info3 = new XmlDocumentSerializationInfo(doc3); Foo o3 = (Foo)info3.GetValue(null); zipinpstream.Close(); zipfile.Close(); t2 = DateTime.Now; dt = t2-t1; Console.WriteLine("Document restored, duration {0}.",dt); }
/// <summary> /// Compile the given XML file to a binary XML file in the given output folder. /// </summary> public void Build() { #if DEBUG //Debugger.Launch(); #endif // Prepare folder var outputFolder = Path.GetDirectoryName(path); if (!Directory.Exists(outputFolder)) { Directory.CreateDirectory(outputFolder); } // Sign apk? const bool sign = true; // Collect entries var entries = new List <ApkEntry>(); entries.Add(new ApkEntry("AndroidManifest.xml", ManifestPath)); entries.AddRange(DexFiles.Select(dexFile => new ApkEntry(Path.GetFileName(dexFile), dexFile))); // Collect map files var mapFiles = MapFiles.Select(p => new MapFile(p)).ToList(); // Collect resource files var resourceEntries = new List <ApkEntry>(); if (!string.IsNullOrEmpty(ResourcesFolder)) { CollectResources(resourceEntries, ResourcesFolder, ResourcesFolder); entries.AddRange(resourceEntries); } // Collect embedded resources as assets foreach (var assembly in Assemblies) { var assets = new List <ApkEntry>(); CollectAssets(assets, assembly); entries.AddRange(assets); } // Collect native code libs CollectNativeCodeLibs(entries); // Load free apps key (if any) string freeAppKey = null; if (!string.IsNullOrEmpty(FreeAppsKeyPath)) { freeAppKey = File.ReadAllText(FreeAppsKeyPath); } // Build ZIP var manifest = new MetaInfManifestBuilder(); var signature = new MetaInfCertSfBuilder(manifest); var rsa = new MetaInfCertRsaBuilder(signature, PfxFile, PfxPassword, CertificateThumbprint, freeAppKey, PackageName); // Build signatures if (sign) { foreach (var entry in entries) { manifest.AddSha1Digest(entry.Name, entry.Data); signature.AddSha1Digest(entry.Name, entry.Data); } } // Create zip string md5FingerPrint = null; string sha1FingerPrint = null; using (var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write)) { using (var zipStream = new ZipOutputStream(fileStream) { UseZip64 = UseZip64.Off }) { zipStream.SetLevel(9); zipStream.PutNextEntry(new ZipEntry("META-INF/MANIFEST.MF") { CompressionMethod = CompressionMethod.Deflated }); manifest.WriteTo(zipStream); zipStream.CloseEntry(); if (sign) { zipStream.PutNextEntry(new ZipEntry("META-INF/LE-C0FC2.SF") { CompressionMethod = CompressionMethod.Deflated }); signature.WriteTo(zipStream); zipStream.CloseEntry(); zipStream.PutNextEntry(new ZipEntry("META-INF/LE-C0FC2.RSA") { CompressionMethod = CompressionMethod.Deflated }); rsa.WriteTo(zipStream, out md5FingerPrint, out sha1FingerPrint); zipStream.CloseEntry(); } foreach (var entry in entries) { var entryName = entry.Name.Replace('\\', '/'); zipStream.PutNextEntry(new ZipEntry(entryName) { CompressionMethod = GetCompressionMethod(entryName) }); entry.WriteTo(zipStream); zipStream.CloseEntry(); } } } // Save MD5 fingerprint var md5FingerPrintPath = Path.ChangeExtension(path, ".md5"); File.WriteAllText(md5FingerPrintPath, md5FingerPrint ?? string.Empty); // Save SHA1 fingerprint var sha1FingerPrintPath = Path.ChangeExtension(path, ".sha1"); File.WriteAllText(sha1FingerPrintPath, sha1FingerPrint ?? string.Empty); // Merge map files var mapFile = MergeMapFiles(mapFiles); mapFile.Save(MapFilePath); #if DEBUG // Create RSA using ( var fileStream = new FileStream(Path.Combine(outputFolder, "CERT.RSA"), FileMode.Create, FileAccess.Write)) { rsa.WriteTo(fileStream, out md5FingerPrint, out sha1FingerPrint); } #endif }
public static void TestBinarySerializationZipped(int len) { DateTime t1; TimeSpan dt; double[] arr = new double[len]; for(int i=0;i<arr.Length;i++) { arr[i] = Math.PI*Math.Sqrt(i); } // FileStream fs = new FileStream(@"C:\TEMP\testbinformat.bin", FileMode.Create); System.IO.FileStream zipoutfile = System.IO.File.Create(@"C:\temp\xmltest03.xml.zip"); ZipOutputStream fs = new ZipOutputStream(zipoutfile); ZipEntry ZipEntry = new ZipEntry("Table/Table1.xml"); fs.PutNextEntry(ZipEntry); fs.SetLevel(0); // Construct a BinaryFormatter and use it to serialize the data to the stream. System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new BinaryFormatter(); t1 = DateTime.Now; try { formatter.Serialize(fs, arr); } catch (SerializationException e) { Console.WriteLine("Failed to serialize. Reason: " + e.Message); throw; } finally { fs.Flush(); fs.Close(); } dt = DateTime.Now - t1; Console.WriteLine("Duration: {0}",dt); }
private static bool ZipFileDictory(string FolderToZip, ZipOutputStream s, string ParentFolderName, bool separate, string[] files, string[] dirs) { bool res = true; string[] folders, filenames; ZipEntry entry = null; FileStream fs = null; Crc32 crc = new Crc32(); try { //创建当前文件夹 entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/")); //加上 “/” 才会当成是文件夹创建 s.PutNextEntry(entry); s.Flush(); //先压缩文件,再递归压缩文件夹 if (separate) { filenames = files; } else { filenames = Directory.GetFiles(FolderToZip); } foreach (string file in filenames) { //打开压缩文件 fs = File.OpenRead(file); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); string p = Path.GetFileName(FolderToZip); if (p.Length < 1) { p = Path.GetFileName(file); } else { p += "/" + Path.GetFileName(file); } entry = new ZipEntry(Path.Combine(ParentFolderName, p)); entry.DateTime = DateTime.Now; entry.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); } } catch { res = false; } finally { if (fs != null) { fs.Close(); fs = null; } if (entry != null) { entry = null; } GC.Collect(); GC.Collect(1); } if (separate) { folders = dirs; } else { folders = Directory.GetDirectories(FolderToZip); } foreach (string folder in folders) { if (folder.Equals(BackUpPath, StringComparison.CurrentCultureIgnoreCase)) { continue; } else if (!ZipFileDictory(folder, s, Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip)), false, null, null)) { return(false); } } return(res); }
public static void CreateZip(string[] filesToZip, string destDir, string zipFileName) { try { string stZipPath = destDir + zipFileName; // TextLogger2.Log("Starting compression..." ); //ZipOutputStream zipOutput = null; if (File.Exists(stZipPath)) { //FileInfo ff = new System.IO.FileInfo(stZipPath); //File.SetAttributes(stZipPath, FileAttributes.Normal); File.Delete(stZipPath); } Crc32 crc = new Crc32(); using (FileStream fs1 = new FileStream(stZipPath, FileMode.Create,FileAccess.ReadWrite,FileShare.Delete)) { using (ZipOutputStream zipOutput = new ZipOutputStream(fs1)) { zipOutput.SetLevel(6); // 0 - store only to 9 - means best compression // TextLogger2.Log(filesToZip.Length + " file(s) to zip."); int index = 0; foreach (string file in filesToZip) { FileInfo fi = new System.IO.FileInfo(file); ZipEntry entry = new ZipEntry(fi.Name); using (FileStream fs = File.OpenRead(fi.FullName)) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); //Create the right arborescence within the archive //string stFileName = fi.FullName.Remove(0, destDir.Length + 1); entry.DateTime = DateTime.Now; entry.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; zipOutput.PutNextEntry(entry); zipOutput.Write(buffer, 0, buffer.Length); } } } } //zipOutput.Finish(); //zipOutput.Close(); //fs1.Flush(); //fs1.Close(); //Force clean up GC.Collect(); //zipOutput = null; //TextLogger2.Log("Compression Successful."); } catch (Exception ex) { throw ex; } }
/// <summary> /// 压缩文件夹(递归) /// </summary> /// <param name="folderToZip">待压缩文件夹路径</param> /// <param name="zipOutputStream"></param> /// <param name="parentFolderName">压缩包内相对文件夹</param> private static bool ZipDirectory(string folderToZip, ZipOutputStream zipOutputStream, string parentFolderName = "") { if (zipOutputStream == null) { throw new ArgumentNullException(nameof(zipOutputStream)); } if (string.IsNullOrWhiteSpace(folderToZip)) { throw new ArgumentException("Value cannot be null or whitespace.", nameof(folderToZip)); } if (!Directory.Exists(folderToZip)) { throw new DirectoryNotFoundException($"文件夹不存在:{folderToZip}"); } var result = true; try { //创建当前文件夹 var relativeFolder = Path.Combine(parentFolderName, $"{Path.GetFileName(folderToZip)}/"); var zipEntry = new ZipEntry(relativeFolder) { DateTime = GetDirLastModifyTime(folderToZip) }; zipOutputStream.PutNextEntry(zipEntry); zipOutputStream.Flush(); //先压缩文件,再递归压缩文件夹 var filePathArray = Directory.GetFiles(folderToZip); foreach (string filePath in filePathArray) { using (var fileStream = File.OpenRead(filePath)) { zipEntry = new ZipEntry(Path.Combine(relativeFolder, Path.GetFileName(filePath))) { DateTime = GetFileLastModifyTime(filePath), Size = fileStream.Length }; zipOutputStream.PutNextEntry(zipEntry); int sizeRead; var buffer = new byte[2048]; while ((sizeRead = fileStream.Read(buffer, 0, buffer.Length)) > 0) { zipOutputStream.Write(buffer, 0, sizeRead); } } } } catch { result = false; } var folders = Directory.GetDirectories(folderToZip); foreach (string folder in folders) { if (!ZipDirectory(folder, zipOutputStream, Path.Combine(parentFolderName, Path.GetFileName(folderToZip)))) { return(false); } } return(result); }
/// <summary> /// Main method /// </summary> /// <param name="stZipPath">path of the archive wanted</param> /// <param name="stDirToZip">path of the directory we want to create, without ending backslash</param> public static void CreateZip(string stZipPath, string stDirToZip) { try { //Sanitize inputs stDirToZip = Path.GetFullPath(stDirToZip); stZipPath = Path.GetFullPath(stZipPath); TextLogger2.Log("Zip directory " + stDirToZip); //Recursively parse the directory to zip Stack<FileInfo> stackFiles = DirExplore(stDirToZip); ZipOutputStream zipOutput = null; if (File.Exists(stZipPath)) File.Delete(stZipPath); Crc32 crc = new Crc32(); zipOutput = new ZipOutputStream(File.Create(stZipPath)); zipOutput.SetLevel(6); // 0 - store only to 9 - means best compression TextLogger2.Log(stackFiles.Count + " files to zip.\n"); int index = 0; foreach (FileInfo fi in stackFiles) { ++index; //int percent = (int)((float)index / ((float)stackFiles.Count / 100)); //if (percent % 1 == 0) //{ // Console.CursorLeft = 0; // Console.Write(_stSchon[index % _stSchon.Length].ToString() + " " + percent + "% done."); //} FileStream fs = File.OpenRead(fi.FullName); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); //Create the right arborescence within the archive string stFileName = fi.FullName.Remove(0, stDirToZip.Length + 1); ZipEntry entry = new ZipEntry(stFileName); entry.DateTime = DateTime.Now; // set Size and the crc, because the information // about the size and crc should be stored in the header // if it is not set it is automatically written in the footer. // (in this case size == crc == -1 in the header) // Some ZIP programs have problems with zip files that don't store // the size and crc in the header. entry.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; zipOutput.PutNextEntry(entry); zipOutput.Write(buffer, 0, buffer.Length); } zipOutput.Finish(); zipOutput.Close(); zipOutput = null; } catch (Exception) { throw; } }
public static bool saveCurrentConfig(string modFolder, string configName) { createConfigFolder(); if (!Directory.Exists(modFolder)) { return(false); } var files = Directory.GetFiles(modFolder); if (files == null || files.Length <= 0) { return(false); } var zipFile = savedConfigFolder + "\\" + configName + ".zip"; if (File.Exists(zipFile)) { var result = MessageBox.Show("Config '" + configName + "' already exists!\nWould you like to overwrite it?", "Configuration Duplicate!", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { File.Delete(zipFile); } else { return(false); } } var destination = File.Create(zipFile); var zipStream = new ZipOutputStream(destination); zipStream.SetLevel(3); var folderOffset = modFolder.Length + (modFolder.EndsWith("\\") ? 0 : 1); var current = 0l; var progressBar = new ZipProgressBar((int)getTotalSize(files)); progressBar.Show(); foreach (string modFile in files) { if (File.Exists(modFile) && (ModFile.isModFile(modFile) || modFile.EndsWith(".desc"))) { var info = new FileInfo(modFile); var entryName = modFile.Substring(folderOffset); entryName = ZipEntry.CleanName(entryName); var newEntry = new ZipEntry(entryName); newEntry.DateTime = info.LastWriteTime; newEntry.Size = info.Length; zipStream.PutNextEntry(newEntry); var buffer = new byte[4096]; using (var streamReader = File.OpenRead(modFile)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); current += info.Length; progressBar.progressBar.Value = (int)min(progressBar.progressBar.Maximum, (progressBar.progressBar.Value + info.Length)); } } progressBar.Close(); zipStream.IsStreamOwner = true; zipStream.Close(); return(true); }
/// <summary> /// Adds the file specified in <paramref name="filePath"/> to the ZIP archive. If <paramref name="fileNameForZip"/> /// is specified, use that filename as the name of the file in the ZIP archive. /// </summary> /// <param name="zos">The ZipOutputStream (ZIP archive) the media object file is to be added to.</param> /// <param name="filePath">The full path to the media object file to be added to the ZIP archive. /// Ex: C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\desert sunsets\zOpt_sonorandesert.jpg</param> /// <param name="fileNameForZip">The full path to the file whose name is to be used to name the file specified /// by <paramref name="filePath"/> in the ZIP archive. If null or empty, the actual filename is used. This path /// does not have to refer to an existing file on disk, but it must begin with <paramref name="basePath"/>. /// Ex: C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\desert sunsets\sonorandesert.jpg</param> /// <param name="basePath">The full path to the directory containing the highest-level media file to be added /// to the ZIP archive. Must include trailing slash. Ex: C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\</param> /// <param name="isImage">Indicates whether the file specified in <paramref name="filePath"/> is an image. If it /// is, and <paramref name="applyWatermark"/> is <c>true</c>, a watermark is applied to the image as it is inserted /// into the archive.</param> /// <param name="applyWatermark">Indicates whether to apply a watermark to images as they are added to the archive. /// This parameter is ignored when <paramref name="isImage"/> is <c>false</c>. When this parameter is <c>true</c>, the /// <paramref name="galleryId" /> must be specified.</param> /// <param name="galleryId">The ID for the gallery associated with the <paramref name="filePath" />. Since each gallery can /// have its own watermark, this value is used to ensure the correct watermark is used. This parameter is ignored when /// <paramref name="isImage" /> or <paramref name="applyWatermark" /> is <c>false</c>.</param> /// <exception cref="ArgumentException">Thrown when <paramref name="isImage" /> is <c>true</c>, <paramref name="applyWatermark" /> /// is <c>true</c> and the <paramref name="galleryId" /> is <see cref="Int32.MinValue" />.</exception> private static void AddFileZipEntry(ZipOutputStream zos, string filePath, string fileNameForZip, string basePath, bool isImage, bool applyWatermark, int galleryId) { if (isImage && applyWatermark && (galleryId == int.MinValue)) { throw new ArgumentException("You must specify a gallery ID when the isImage and applyWatermark parameters are set to true."); } int bufferSize = AppSetting.Instance.MediaObjectDownloadBufferSize; byte[] buffer = new byte[bufferSize]; #region Determine ZIP entry name // Get name of the file as it will be stored in the ZIP archive. This is the fragment of the full file path // after the base path. Ex: If basePath="C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\" // and filePath="C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\desert sunsets\zOpt_sonorandesert.jpg", // then zipEntryName="desert sunsets\zOpt_sonorandesert.jpg". The ZIP algorithm will automatically sense the // embedded directory ("desert sunsets") and create it. string zipEntryName; if (String.IsNullOrEmpty(fileNameForZip)) { zipEntryName = filePath.Replace(basePath, String.Empty); } else { zipEntryName = fileNameForZip.Replace(basePath, String.Empty); } #endregion using (Stream stream = CreateStream(filePath, isImage, applyWatermark, galleryId)) { ZipEntry entry = new ZipEntry(zipEntryName); entry.Size = stream.Length; zos.PutNextEntry(entry); int byteCount; while ((byteCount = stream.Read(buffer, 0, buffer.Length)) > 0) { zos.Write(buffer, 0, byteCount); } } }
private void writeKMLFirstPerson(string filename) { StreamWriter stream = new StreamWriter(File.Open(filename, FileMode.Create)); System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); string header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><kml xmlns=\"http://www.opengis.net/kml/2.2\" xmlns:gx=\"http://www.google.com/kml/ext/2.2\" xmlns:kml=\"http://www.opengis.net/kml/2.2\" xmlns:atom=\"http://www.w3.org/2005/Atom\">\n <Document> <name>Paths</name> <description>Path</description>\n <Style id=\"yellowLineGreenPoly\"> <LineStyle> <color>7f00ffff</color> <width>4</width> </LineStyle> <PolyStyle> <color>7f00ff00</color> </PolyStyle> </Style>\n "; stream.Write(header); StringBuilder kml = new StringBuilder(); StringBuilder data = new StringBuilder(); double lastlat = 0; double lastlong = 0; int gpspackets = 0; int lastgpspacket = 0; foreach (Data mod in flightdata) { if (mod.model.Location.latitude == 0) { continue; } gpspackets++; if (lastlat == mod.model.Location.latitude && lastlong == mod.model.Location.longitude) { continue; } // double speed 0.05 - assumeing 10hz in log file // 1 speed = 0.1 10 / 1 = 0.1 data.Append(@" <gx:FlyTo> <gx:duration>" + ((gpspackets - lastgpspacket) * 0.1) + @"</gx:duration> <gx:flyToMode>smooth</gx:flyToMode> <Camera> <longitude>" + mod.model.Location.longitude.ToString(new System.Globalization.CultureInfo("en-US")) + @"</longitude> <latitude>" + mod.model.Location.latitude.ToString(new System.Globalization.CultureInfo("en-US")) + @"</latitude> <altitude>" + mod.model.Location.altitude.ToString(new System.Globalization.CultureInfo("en-US")) + @"</altitude> <roll>" + mod.model.Orientation.roll.ToString(new System.Globalization.CultureInfo("en-US")) + @"</roll> <tilt>" + (90 - mod.model.Orientation.tilt).ToString(new System.Globalization.CultureInfo("en-US")) + @"</tilt> <heading>" + mod.model.Orientation.heading.ToString(new System.Globalization.CultureInfo("en-US")) + @"</heading> <altitudeMode>absolute</altitudeMode> </Camera> </gx:FlyTo> "); lastlat = mod.model.Location.latitude; lastlong = mod.model.Location.longitude; lastgpspacket = gpspackets; } kml.Append(@" <Folder> <name>Flight</name> <gx:Tour> <name>Flight Do</name> <gx:Playlist> " + data + @"</gx:Playlist> </gx:Tour> </Folder> </Document> </kml> "); stream.Write(kml.ToString()); stream.Close(); // create kmz - aka zip file FileStream fs = File.Open(filename.Replace(".log-fp.kml", "-fp.kmz"), FileMode.Create); ZipOutputStream zipStream = new ZipOutputStream(fs); zipStream.SetLevel(9); //0-9, 9 being the highest level of compression zipStream.UseZip64 = UseZip64.Off; // older zipfile // entry 1 string entryName = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction ZipEntry newEntry = new ZipEntry(entryName); newEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(newEntry); // Zip the file in buffered chunks // the "using" will close the stream even if an exception occurs byte[] buffer = new byte[4096]; using (FileStream streamReader = File.OpenRead(filename)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); File.Delete(filename); filename = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + "block_plane_0.dae"; // entry 2 entryName = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction newEntry = new ZipEntry(entryName); newEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(newEntry); // Zip the file in buffered chunks // the "using" will close the stream even if an exception occurs buffer = new byte[4096]; using (FileStream streamReader = File.OpenRead(filename)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); zipStream.IsStreamOwner = true; // Makes the Close also Close the underlying stream zipStream.Close(); positionindex = 0; modelist.Clear(); flightdata.Clear(); position = new List <Core.Geometry.Point3D> [200]; cmd.Clear(); }
/// <summary> /// Adds the specified <paramref name="content" /> to the ZIP archive, giving it the specified <paramref name="fileNameForZip" />. /// </summary> /// <param name="zos">The ZipOutputStream (ZIP archive) the <paramref name="content" /> is to be added to.</param> /// <param name="content">The text to be added to the ZIP archive.</param> /// <param name="fileNameForZip">The name to be given to the <paramref name="content" /> within the ZIP archive.</param> private static void AddFileZipEntry(ZipOutputStream zos, string content, string fileNameForZip) { int bufferSize = AppSetting.Instance.MediaObjectDownloadBufferSize; byte[] buffer = new byte[bufferSize]; using (Stream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(content))) { ZipEntry entry = new ZipEntry(fileNameForZip); entry.Size = stream.Length; zos.PutNextEntry(entry); int byteCount; while ((byteCount = stream.Read(buffer, 0, buffer.Length)) > 0) { zos.Write(buffer, 0, byteCount); } } }
/** * Save relationships into the part. * * @param rels * The relationships collection to marshall. * @param relPartName * Part name of the relationship part to marshall. * @param zos * Zip output stream in which to save the XML content of the * relationships serialization. */ public static bool MarshallRelationshipPart( PackageRelationshipCollection rels, PackagePartName relPartName, ZipOutputStream zos) { // Building xml XmlDocument xmlOutDoc = new XmlDocument(); // make something like <Relationships // xmlns="http://schemas.openxmlformats.org/package/2006/relationships"> System.Xml.XmlNamespaceManager xmlnsManager = new System.Xml.XmlNamespaceManager(xmlOutDoc.NameTable); xmlnsManager.AddNamespace("x", PackageNamespaces.RELATIONSHIPS); XmlNode root = xmlOutDoc.AppendChild(xmlOutDoc.CreateElement(PackageRelationship.RELATIONSHIPS_TAG_NAME, PackageNamespaces.RELATIONSHIPS)); // <Relationship // TargetMode="External" // Id="rIdx" // Target="http://www.custom.com/images/pic1.jpg" // Type="http://www.custom.com/external-resource"/> Uri sourcePartURI = PackagingUriHelper .GetSourcePartUriFromRelationshipPartUri(relPartName.URI); foreach (PackageRelationship rel in rels) { // the relationship element XmlElement relElem = xmlOutDoc.CreateElement(PackageRelationship.RELATIONSHIP_TAG_NAME, PackageNamespaces.RELATIONSHIPS); // the relationship ID relElem.SetAttribute(PackageRelationship.ID_ATTRIBUTE_NAME, rel.Id); // the relationship Type relElem.SetAttribute(PackageRelationship.TYPE_ATTRIBUTE_NAME, rel .RelationshipType); // the relationship Target String targetValue; Uri uri = rel.TargetUri; if (rel.TargetMode == TargetMode.External) { // Save the target as-is - we don't need to validate it, // alter it etc targetValue = uri.OriginalString; // add TargetMode attribute (as it is external link external) relElem.SetAttribute( PackageRelationship.TARGET_MODE_ATTRIBUTE_NAME, "External"); } else { targetValue = PackagingUriHelper.RelativizeUri( sourcePartURI, rel.TargetUri, true).ToString(); } relElem.SetAttribute(PackageRelationship.TARGET_ATTRIBUTE_NAME, targetValue); xmlOutDoc.DocumentElement.AppendChild(relElem); } xmlOutDoc.Normalize(); // String schemaFilename = Configuration.getPathForXmlSchema()+ // File.separator + "opc-relationships.xsd"; // Save part in zip ZipEntry ctEntry = new ZipEntry(ZipHelper.GetZipURIFromOPCName( relPartName.URI.ToString()).OriginalString); try { zos.PutNextEntry(ctEntry); StreamHelper.SaveXmlInStream(xmlOutDoc, zos); zos.CloseEntry(); } catch (IOException e) { logger.Log(POILogger.ERROR, "Cannot create zip entry " + relPartName, e); return(false); } return(true); // success }
void NewCreateZip(SPListItem item, ZipOutputStream zs) { SPSecurity.RunWithElevatedPrivileges(delegate { if (null != item.Folder) { foreach (SPFile file in item.Folder.Files) { NewCreateZip(file.Item, zs); } foreach (SPFolder folder in item.Folder.SubFolders) { NewCreateZip(folder.Item, zs); } } else { ZipEntry entry = new ZipEntry(item.File.Url.Substring(iParentFolderLength)); zs.PutNextEntry(entry); int intReadLength = 0; Stream s = item.File.OpenBinaryStream(); do { byte[] buffer = new byte[1024]; intReadLength = s.Read(buffer, 0, buffer.Length); zs.Write(buffer, 0, intReadLength); } while (intReadLength == 1024); s.Dispose(); s.Close(); } }); }
public static int avg = 1024 * 1024 * 100;//100MB写一次 ///<summary> ///压缩文件和文件夹不压缩顶级目录 ///</summary> ///<param name="FolderToZip">待压缩的文件夹,全路径格式</param> ///<param name="ZipedFile">压缩后生成的压缩文件名,全路径格式</param> ///<returns>压缩是否成功</returns> public static bool ZipNo(string FolderToZip, string ZipedFile) { if (!Directory.Exists(FolderToZip)) { return(false); } if (ZipedFile == string.Empty) { ZipedFile = FolderToZip + ".zip"; } ZipOutputStream s = new ZipOutputStream(File.Create(ZipedFile)); s.SetLevel(6); string[] filenames = Directory.GetFiles(FolderToZip); ZipEntry entry = null; FileStream fs = null; Crc32 crc = new Crc32(); foreach (string file in filenames) { //压缩文件 fs = File.OpenRead(file); byte[] buffer = new byte[avg]; entry = new ZipEntry(Path.GetFileName(file)); entry.DateTime = DateTime.Now; entry.Size = fs.Length; s.PutNextEntry(entry); for (int i = 0; i < fs.Length; i += avg) { if (i + avg > fs.Length) { //不足100MB的部分写剩余部分 buffer = new byte[fs.Length - i]; } fs.Read(buffer, 0, buffer.Length); s.Write(buffer, 0, buffer.Length); } } if (fs != null) { fs.Close(); fs = null; } if (entry != null) { entry = null; } GC.Collect(); GC.Collect(1); //压缩目录 string[] folders = Directory.GetDirectories(FolderToZip); foreach (string folder in folders) { if (!ZipFileDictory(folder, s, "")) { return(false); } } s.Finish(); s.Close(); return(true); }
internal void Save(Stream stream) { var enc = Encoding.UTF8; ZipOutputStream os = new ZipOutputStream(stream, true); os.CompressionLevel = (OfficeOpenXml.Packaging.Ionic.Zlib.CompressionLevel)_compression; /**** ContentType****/ var entry = os.PutNextEntry("[Content_Types].xml"); byte[] b = enc.GetBytes(GetContentTypeXml()); os.Write(b, 0, b.Length); /**** Top Rels ****/ _rels.WriteZip(os, "_rels\\.rels"); ZipPackagePart ssPart=null; foreach(var part in Parts.Values) { if (part.ContentType != ExcelPackage.contentTypeSharedString) { part.WriteZip(os); } else { ssPart = part; } } //Shared strings must be saved after all worksheets. The ss dictionary is populated when that workheets are saved (to get the best performance). if (ssPart != null) { ssPart.WriteZip(os); } os.Flush(); os.Close(); os.Dispose(); //return ms; }
///<summary> ///递归压缩文件夹方法 ///</summary> ///<param name="FolderToZip"></param> ///<param name="s"></param> ///<param name="ParentFolderName"></param> private static bool ZipFileDictory(string FolderToZip, ZipOutputStream s, string ParentFolderName) { bool res = true; string[] folders, filenames; ZipEntry entry = null; FileStream fs = null; Crc32 crc = new Crc32(); try { //创建当前文件夹 entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/")); //加上 “/” 才会当成是文件夹创建 s.PutNextEntry(entry); s.Flush(); //先压缩文件,再递归压缩文件夹 filenames = Directory.GetFiles(FolderToZip); foreach (string file in filenames) { //打开压缩文件 fs = File.OpenRead(file); byte[] buffer = new byte[avg]; entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/" + Path.GetFileName(file))); entry.DateTime = DateTime.Now; entry.Size = fs.Length; s.PutNextEntry(entry); for (int i = 0; i < fs.Length; i += avg) { if (i + avg > fs.Length) { //不足100MB的部分写剩余部分 buffer = new byte[fs.Length - i]; } fs.Read(buffer, 0, buffer.Length); s.Write(buffer, 0, buffer.Length); } } } catch (Exception ex) { res = false; } finally { if (fs != null) { fs.Close(); fs = null; } if (entry != null) { entry = null; } GC.Collect(); GC.Collect(1); } folders = Directory.GetDirectories(FolderToZip); foreach (string folder in folders) { if (!ZipFileDictory(folder, s, Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip)))) { return(false); } } return(res); }
/// <summary> /// 递归遍历目录 /// </summary> /// <param name="strDirectory">The directory.</param> /// <param name="s">The ZipOutputStream Object.</param> /// <param name="parentPath">The parent path.</param> /// <param name="ignoreSuffixs">ignore files with suffix</param> private static void ZipSetp(string strDirectory, ZipOutputStream s, string parentPath, params string[] ignoreSuffixs) { if (strDirectory[strDirectory.Length - 1] != Path.DirectorySeparatorChar) { strDirectory += Path.DirectorySeparatorChar; } Crc32 crc = new Crc32(); string[] filenames = Directory.GetFileSystemEntries(strDirectory); for (int i = 0; i < filenames.Length; i++)// 遍历所有的文件和目录 { string file = filenames[i].Replace("\\", "/"); if (Directory.Exists(file))// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件 { string pPath = parentPath; pPath += file.Substring(file.LastIndexOf("/") + 1); pPath += "/"; ZipSetp(file, s, pPath, ignoreSuffixs); } else // 否则直接压缩文件 { #region ignore files bool ignore = false; if (ignoreSuffixs != null) { foreach (var itemSuffix in ignoreSuffixs) { string suffix = FileHelper.getFileTypeByPath(file); if (suffix == itemSuffix) { ignore = true; break; } } } if (ignore) { continue; } #endregion //打开压缩文件 using (FileStream fs = File.OpenRead(file)) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); string fileName = parentPath + file.Substring(file.LastIndexOf("/") + 1); ZipEntry entry = new ZipEntry(fileName); entry.DateTime = DateTime.Now; entry.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); } } } }
/// <summary> /// 递归压缩文件夹的内部方法 /// </summary> /// <param name="folderToZip">要压缩的文件夹路径</param> /// <param name="zipStream">压缩输出流</param> /// <param name="parentFolderName">此文件夹的上级文件夹</param> /// <returns></returns> private static bool ZipDirectory(string folderToZip, ZipOutputStream zipStream, string parentFolderName) { bool result = true; string[] folders, files; ZipEntry ent = null; FileStream fs = null; Crc32 crc = new Crc32(); try { ent = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/")); zipStream.PutNextEntry(ent); zipStream.Flush(); files = Directory.GetFiles(folderToZip); foreach (string file in files) { fs = File.OpenRead(file); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); ent = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/" + Path.GetFileName(file))); ent.DateTime = DateTime.Now; ent.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); ent.Crc = crc.Value; zipStream.PutNextEntry(ent); zipStream.Write(buffer, 0, buffer.Length); } } catch { result = false; } finally { if (fs != null) { fs.Close(); fs.Dispose(); } if (ent != null) { ent = null; } GC.Collect(); GC.Collect(1); } folders = Directory.GetDirectories(folderToZip); foreach (string folder in folders) { if (!ZipDirectory(folder, zipStream, folderToZip)) { return(false); } } return(result); }
/// <summary> /// Creates the zip file. /// </summary> protected override void ExecuteTask() { ZipOutputStream zOutstream = null; Log(Level.Info, "Zipping {0} files to '{1}'.", ZipFileSets.FileCount, ZipFile.FullName); try { if (!Directory.Exists(ZipFile.DirectoryName)) { Directory.CreateDirectory(ZipFile.DirectoryName); } // set encoding to use for filenames and comment ZipConstants.DefaultCodePage = Encoding.CodePage; zOutstream = new ZipOutputStream(ZipFile.Create()); // set compression level zOutstream.SetLevel(ZipLevel); // set comment if (!String.IsNullOrEmpty(Comment)) { zOutstream.SetComment(Comment); } foreach (ZipFileSet fileset in ZipFileSets) { string basePath = fileset.BaseDirectory.FullName; if (Path.GetPathRoot(basePath) != basePath) { basePath = Path.GetDirectoryName(basePath + Path.DirectorySeparatorChar); } // add files to zip foreach (string file in fileset.FileNames) { // ensure file exists (in case "asis" was used) if (!File.Exists(file)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "File '{0}' does not exist.", file), Location); } // the name of the zip entry string entryName; // determine name of the zip entry if (!Flatten && file.StartsWith(basePath)) { entryName = file.Substring(basePath.Length); if (entryName.Length > 0 && entryName[0] == Path.DirectorySeparatorChar) { entryName = entryName.Substring(1); } // remember that directory was added to zip file, so // that we won't add it again later string dir = Path.GetDirectoryName(file); if (_addedDirs[dir] == null) { _addedDirs[dir] = dir; } } else { // flatten directory structure entryName = Path.GetFileName(file); } // add prefix if specified if (fileset.Prefix != null) { entryName = fileset.Prefix + entryName; } // ensure directory separators are understood on linux if (Path.DirectorySeparatorChar == '\\') { entryName = entryName.Replace(@"\", "/"); } // perform duplicate checking if (_fileEntries.ContainsKey(entryName)) { switch (DuplicateHandling) { case DuplicateHandling.Add: break; case DuplicateHandling.Fail: throw new BuildException(string.Format( CultureInfo.InvariantCulture, "Duplicate file '{0}' was found.", entryName), Location.UnknownLocation); case DuplicateHandling.Preserve: // skip current entry continue; default: throw new BuildException(string.Format( CultureInfo.InvariantCulture, "Duplicate value '{0}' is not supported.", DuplicateHandling.ToString()), Location.UnknownLocation); } } // create zip entry ZipEntry entry = new ZipEntry(entryName); // store entry (to allow for duplicate checking) _fileEntries[entryName] = null; // set date/time stamp on zip entry if (Stamp != DateTime.MinValue) { entry.DateTime = Stamp; } else { entry.DateTime = File.GetLastWriteTime(file); } // write file content to stream in small chuncks using (FileStream fs = File.OpenRead(file)) { // set size for backward compatibility with older unzip entry.Size = fs.Length; Log(Level.Verbose, "Adding {0}.", entryName); // write file to zip file zOutstream.PutNextEntry(entry); byte[] buffer = new byte[50000]; while (true) { int bytesRead = fs.Read(buffer, 0, buffer.Length); if (bytesRead == 0) { break; } zOutstream.Write(buffer, 0, bytesRead); } } } // add (possibly empty) directories to zip if (IncludeEmptyDirs) { foreach (string directory in fileset.DirectoryNames) { // skip directories that were already added when the // files were added if (_addedDirs[directory] != null) { continue; } // skip directories that are not located beneath the base // directory if (!directory.StartsWith(basePath) || directory.Length <= basePath.Length) { continue; } // determine zip entry name string entryName = directory.Substring(basePath.Length + 1); // add prefix if specified if (fileset.Prefix != null) { entryName = fileset.Prefix + entryName; } // ensure directory separators are understood on linux if (Path.DirectorySeparatorChar == '\\') { entryName = entryName.Replace(@"\", "/"); } if (!entryName.EndsWith("/")) { // trailing directory signals to #ziplib that we're // dealing with directory entry entryName += "/"; } // create directory entry ZipEntry entry = new ZipEntry(entryName); // set size for backward compatibility with older unzip entry.Size = 0L; // write directory to zip file zOutstream.PutNextEntry(entry); } } } zOutstream.Close(); zOutstream.Finish(); } catch (Exception ex) { // close the zip output stream if (zOutstream != null) { zOutstream.Close(); } // delete the (possibly corrupt) zip file if (ZipFile.Exists) { ZipFile.Delete(); } throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Zip file '{0}' could not be created.", ZipFile.FullName), Location, ex); } finally { CleanUp(); } }
private void writeKML(string filename) { SharpKml.Dom.AltitudeMode altmode = SharpKml.Dom.AltitudeMode.Absolute; if (MainV2.cs.firmware == MainV2.Firmwares.ArduPlane) { altmode = SharpKml.Dom.AltitudeMode.Absolute; } else if (MainV2.cs.firmware == MainV2.Firmwares.ArduCopter2) { altmode = SharpKml.Dom.AltitudeMode.RelativeToGround; } Color[] colours = { Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Blue, Color.Indigo, Color.Violet, Color.Pink }; Document kml = new Document(); Tour tour = new Tour() { Name = "First Person View" }; Playlist tourplaylist = new Playlist(); AddNamespace(kml, "gx", "http://www.google.com/kml/ext/2.2"); Style style = new Style(); style.Id = "yellowLineGreenPoly"; style.Line = new LineStyle(new Color32(HexStringToColor("7f00ffff")), 4); PolygonStyle pstyle = new PolygonStyle(); pstyle.Color = new Color32(HexStringToColor("7f00ff00")); style.Polygon = pstyle; kml.AddStyle(style); Style stylet = new Style(); stylet.Id = "track"; SharpKml.Dom.IconStyle ico = new SharpKml.Dom.IconStyle(); LabelStyle lst = new LabelStyle(); lst.Scale = 0; stylet.Icon = ico; ico.Icon = new IconStyle.IconLink(new Uri("http://earth.google.com/images/kml-icons/track-directional/track-none.png")); stylet.Icon.Scale = 0.5; stylet.Label = lst; kml.AddStyle(stylet); // create sub folders Folder planes = new Folder(); planes.Name = "Planes"; kml.AddFeature(planes); Folder points = new Folder(); points.Name = "Points"; kml.AddFeature(points); // coords for line string CoordinateCollection coords = new CoordinateCollection(); int a = 1; int c = -1; DateTime lasttime = DateTime.MaxValue; DateTime starttime = DateTime.MinValue; Color stylecolor = Color.AliceBlue; string mode = ""; if (flightdata.Count > 0) { mode = flightdata[0].mode; } foreach (CurrentState cs in flightdata) { progressBar1.Value = 50 + (int)((float)a / (float)flightdata.Count * 100.0f / 2.0f); progressBar1.Refresh(); if (starttime == DateTime.MinValue) { starttime = cs.datetime; lasttime = cs.datetime; } if (mode != cs.mode || flightdata.Count == a) { c++; LineString ls = new LineString(); ls.AltitudeMode = altmode; ls.Extrude = true; ls.Coordinates = coords; Placemark pm = new Placemark(); pm.Name = c + " Flight Path " + mode; pm.StyleUrl = new Uri("#yellowLineGreenPoly", UriKind.Relative); pm.Geometry = ls; SharpKml.Dom.TimeSpan ts = new SharpKml.Dom.TimeSpan(); ts.Begin = starttime; ts.End = cs.datetime; pm.Time = ts; // setup for next line mode = cs.mode; starttime = cs.datetime; stylecolor = colours[c % (colours.Length - 1)]; Style style2 = new Style(); style2.Line = new LineStyle(new Color32(stylecolor), 4); pm.StyleSelector = style2; kml.AddFeature(pm); coords = new CoordinateCollection(); } coords.Add(new Vector(cs.lat, cs.lng, cs.alt)); SharpKml.Dom.Timestamp tstamp = new SharpKml.Dom.Timestamp(); tstamp.When = cs.datetime; FlyTo flyto = new FlyTo(); flyto.Duration = (cs.datetime - lasttime).TotalMilliseconds / 1000.0; flyto.Mode = FlyToMode.Smooth; SharpKml.Dom.Camera cam = new SharpKml.Dom.Camera(); cam.AltitudeMode = altmode; cam.Latitude = cs.lat; cam.Longitude = cs.lng; cam.Altitude = cs.alt; cam.Heading = cs.yaw; cam.Roll = -cs.roll; cam.Tilt = (90 - (cs.pitch * -1)); cam.GXTimePrimitive = tstamp; flyto.View = cam; //if (Math.Abs(flyto.Duration.Value) > 0.1) { tourplaylist.AddTourPrimitive(flyto); lasttime = cs.datetime; } Placemark pmplane = new Placemark(); pmplane.Name = "Point " + a; pmplane.Time = tstamp; pmplane.Visibility = false; SharpKml.Dom.Location loc = new SharpKml.Dom.Location(); loc.Latitude = cs.lat; loc.Longitude = cs.lng; loc.Altitude = cs.alt; if (loc.Altitude < 0) { loc.Altitude = 0.01; } SharpKml.Dom.Orientation ori = new SharpKml.Dom.Orientation(); ori.Heading = cs.yaw; ori.Roll = -cs.roll; ori.Tilt = -cs.pitch; SharpKml.Dom.Scale sca = new SharpKml.Dom.Scale(); sca.X = 2; sca.Y = 2; sca.Z = 2; Model model = new Model(); model.Location = loc; model.Orientation = ori; model.AltitudeMode = altmode; model.Scale = sca; try { Description desc = new Description(); desc.Text = @"<![CDATA[ <table> <tr><td>Roll: " + model.Orientation.Roll.Value.ToString("0.00") + @" </td></tr> <tr><td>Pitch: " + model.Orientation.Tilt.Value.ToString("0.00") + @" </td></tr> <tr><td>Yaw: " + model.Orientation.Heading.Value.ToString("0.00") + @" </td></tr> <tr><td>Time: " + cs.datetime.ToString("HH:mm:sszzzzzz") + @" </td></tr> </table> "; // ]]>"; pmplane.Description = desc; } catch { } Link link = new Link(); link.Href = new Uri("block_plane_0.dae", UriKind.Relative); model.Link = link; pmplane.Geometry = model; planes.AddFeature(pmplane); /// Placemark pmt = new Placemark(); SharpKml.Dom.Point pnt = new SharpKml.Dom.Point(); pnt.AltitudeMode = altmode; pnt.Coordinate = new Vector(cs.lat, cs.lng, cs.alt); pmt.Name = "" + a; pmt.Description = pmplane.Description; pmt.Time = tstamp; pmt.Geometry = pnt; pmt.StyleUrl = new Uri("#track", UriKind.Relative); points.AddFeature(pmt); a++; } tour.Playlist = tourplaylist; kml.AddFeature(tour); Serializer serializer = new Serializer(); serializer.Serialize(kml); //Console.WriteLine(serializer.Xml); StreamWriter sw = new StreamWriter(filename); sw.Write(serializer.Xml); sw.Close(); // create kmz - aka zip file FileStream fs = File.Open(filename.Replace(Path.GetExtension(filename), ".kmz"), FileMode.Create); ZipOutputStream zipStream = new ZipOutputStream(fs); zipStream.SetLevel(9); //0-9, 9 being the highest level of compression zipStream.UseZip64 = UseZip64.Off; // older zipfile // entry 1 string entryName = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction ZipEntry newEntry = new ZipEntry(entryName); newEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(newEntry); // Zip the file in buffered chunks // the "using" will close the stream even if an exception occurs byte[] buffer = new byte[4096]; using (FileStream streamReader = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); filename = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + "block_plane_0.dae"; // entry 2 entryName = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction newEntry = new ZipEntry(entryName); newEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(newEntry); // Zip the file in buffered chunks // the "using" will close the stream even if an exception occurs buffer = new byte[4096]; using (FileStream streamReader = File.OpenRead(filename)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); zipStream.IsStreamOwner = true; // Makes the Close also Close the underlying stream zipStream.Close(); flightdata.Clear(); }
private static void writeZipEntry(ZipEntry zipEntry, Stream sourceStream, ZipOutputStream zipOutputStream) { zipOutputStream.PutNextEntry(zipEntry); sourceStream.CopyTo(zipOutputStream); }
public void writeKML(string filename) { try { writeGPX(filename); writeRinex(filename); writeWPFile(filename); } catch { } Color[] colours = { Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Blue, Color.Indigo, Color.Violet, Color.Pink }; AltitudeMode altmode = AltitudeMode.absolute; KMLRoot kml = new KMLRoot(); Folder fldr = new Folder("Log"); Style style = new Style(); style.Id = "yellowLineGreenPoly"; style.Add(new LineStyle(HexStringToColor("7f00ffff"), 4)); Style style1 = new Style(); style1.Id = "spray"; style1.Add(new LineStyle(HexStringToColor("4c0000ff"), 0)); style1.Add(new PolyStyle() { Color = HexStringToColor("4c0000ff") }); PolyStyle pstyle = new PolyStyle(); pstyle.Color = HexStringToColor("7f00ff00"); style.Add(pstyle); kml.Document.AddStyle(style); kml.Document.AddStyle(style1); int stylecode = 0xff; int g = -1; foreach (List <Point3D> poslist in position) { g++; if (poslist == null) { continue; } /* * List<PointLatLngAlt> pllalist = new List<PointLatLngAlt>(); * * foreach (var point in poslist) * { * pllalist.Add(new PointLatLngAlt(point.Y, point.X, point.Z, "")); * } * * var ans = Utilities.LineOffset.GetPolygon(pllalist, 2); * * * * while (ans.Count > 0) * { * var first = ans[0]; * var second = ans[1]; * var secondlast = ans[ans.Count - 2]; * var last = ans[ans.Count-1]; * * ans.Remove(first); * ans.Remove(last); * * var polycoords = new BoundaryIs(); * * polycoords.LinearRing = new LinearRing(); * * polycoords.LinearRing.Coordinates.Add(new Point3D(first.Lng, first.Lat, 1)); * polycoords.LinearRing.Coordinates.Add(new Point3D(second.Lng, second.Lat, 1)); * polycoords.LinearRing.Coordinates.Add(new Point3D(secondlast.Lng, secondlast.Lat, 1)); * polycoords.LinearRing.Coordinates.Add(new Point3D(last.Lng, last.Lat, 1)); * polycoords.LinearRing.Coordinates.Add(new Point3D(first.Lng, first.Lat, 1)); * * //if (!IsClockwise(polycoords.LinearRing.Coordinates)) * // polycoords.LinearRing.Coordinates.Reverse(); * * Polygon kmlpoly = new Polygon() { AltitudeMode = AltitudeMode.relativeToGround, Extrude = false, OuterBoundaryIs = polycoords }; * * Placemark pmpoly = new Placemark(); * pmpoly.Polygon = kmlpoly; * pmpoly.name = g + " test"; * pmpoly.styleUrl = "#spray"; * * fldr.Add(pmpoly); * } */ LineString ls = new LineString(); ls.AltitudeMode = altmode; ls.Extrude = true; //ls.Tessellate = true; Coordinates coords = new Coordinates(); coords.AddRange(poslist); ls.coordinates = coords; Placemark pm = new Placemark(); string mode = ""; if (g < modelist.Count) { mode = modelist[g]; } pm.name = g + " Flight Path " + mode; pm.styleUrl = "#yellowLineGreenPoly"; pm.LineString = ls; stylecode = colours[g % (colours.Length - 1)].ToArgb(); Style style2 = new Style(); Color color = Color.FromArgb(0xff, (stylecode >> 16) & 0xff, (stylecode >> 8) & 0xff, (stylecode >> 0) & 0xff); log.Info("colour " + color.ToArgb().ToString("X") + " " + color.ToKnownColor().ToString()); style2.Add(new LineStyle(color, 4)); pm.AddStyle(style2); fldr.Add(pm); } Placemark pmPOS = new Placemark(); pmPOS.name = "POS Message"; pmPOS.LineString = new LineString(); pmPOS.LineString.coordinates = new Coordinates(); Point3D lastPoint3D = new Point3D(); PointLatLngAlt lastplla = PointLatLngAlt.Zero; foreach (var item in PosLatLngAlts) { var newpoint = new Point3D(item.Lng, item.Lat, item.Alt); if (item.GetDistance(lastplla) < 0.1 && lastPoint3D.Z >= (newpoint.Z - 0.3) && lastPoint3D.Z <= (newpoint.Z + 0.3)) { continue; } pmPOS.LineString.coordinates.Add(newpoint); lastPoint3D = newpoint; lastplla = item; if (pmPOS.LineString.coordinates.Count > 20000) { //add current pmPOS.AddStyle(style); fldr.Add(pmPOS); // create new pmPOS = new Placemark(); pmPOS.name = "POS Message - extra"; pmPOS.LineString = new LineString(); pmPOS.LineString.coordinates = new Coordinates(); lastPoint3D = new Point3D(); lastplla = PointLatLngAlt.Zero; } } pmPOS.AddStyle(style); fldr.Add(pmPOS); Folder planes = new Folder(); planes.name = "Planes"; fldr.Add(planes); Folder waypoints = new Folder(); waypoints.name = "Waypoints"; fldr.Add(waypoints); LineString lswp = new LineString(); lswp.AltitudeMode = AltitudeMode.relativeToGround; lswp.Extrude = true; Coordinates coordswp = new Coordinates(); foreach (PointLatLngAlt p1 in cmd) { if (p1.Lng == 0 && p1.Lat == 0) { continue; } coordswp.Add(new Point3D(p1.Lng, p1.Lat, p1.Alt)); } lswp.coordinates = coordswp; Placemark pmwp = new Placemark(); pmwp.name = "Waypoints"; //pm.styleUrl = "#yellowLineGreenPoly"; pmwp.LineString = lswp; if (coordswp.Count > 0) { waypoints.Add(pmwp); } int a = 0; int l = -1; Model lastmodel = null; foreach (Data mod in flightdata) { l++; if (mod.model.Location.latitude == 0) { continue; } if (lastmodel != null) { if (lastmodel.Location.Equals(mod.model.Location)) { continue; } } Placemark pmplane = new Placemark(); pmplane.name = "Plane " + a; pmplane.visibility = false; Model model = mod.model; model.AltitudeMode = altmode; model.Scale.x = 2; model.Scale.y = 2; model.Scale.z = 2; try { pmplane.description = @"<![CDATA[ <table> <tr><td>Roll: " + model.Orientation.roll + @" </td></tr> <tr><td>Pitch: " + model.Orientation.tilt + @" </td></tr> <tr><td>Yaw: " + model.Orientation.heading + @" </td></tr> <tr><td>WP dist " + mod.ntun[2] + @" </td></tr> <tr><td>tar bear " + mod.ntun[3] + @" </td></tr> <tr><td>nav bear " + mod.ntun[4] + @" </td></tr> <tr><td>alt error " + mod.ntun[5] + @" </td></tr> </table> ]]>"; } catch { } try { pmplane.Point = new KmlPoint((float)model.Location.longitude, (float)model.Location.latitude, (float)model.Location.altitude); pmplane.Point.AltitudeMode = altmode; Link link = new Link(); link.href = "block_plane_0.dae"; model.Link = link; pmplane.Model = model; planes.Add(pmplane); } catch { } // bad lat long value lastmodel = mod.model; a++; } kml.Document.Add(fldr); kml.Save(filename); // create kmz - aka zip file FileStream fs = File.Open(filename.ToLower().Replace(".log.kml", ".kmz").Replace(".bin.kml", ".kmz"), FileMode.Create); ZipOutputStream zipStream = new ZipOutputStream(fs); zipStream.SetLevel(9); //0-9, 9 being the highest level of compression zipStream.UseZip64 = UseZip64.Off; // older zipfile // entry 1 string entryName = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction ZipEntry newEntry = new ZipEntry(entryName); newEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(newEntry); // Zip the file in buffered chunks // the "using" will close the stream even if an exception occurs byte[] buffer = new byte[4096]; using (FileStream streamReader = File.OpenRead(filename)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); File.Delete(filename); filename = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + "block_plane_0.dae"; // entry 2 entryName = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction newEntry = new ZipEntry(entryName); newEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(newEntry); // Zip the file in buffered chunks // the "using" will close the stream even if an exception occurs buffer = new byte[4096]; using (FileStream streamReader = File.OpenRead(filename)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); zipStream.IsStreamOwner = true; // Makes the Close also Close the underlying stream zipStream.Close(); positionindex = 0; modelist.Clear(); flightdata.Clear(); position = new List <Core.Geometry.Point3D> [200]; cmd.Clear(); cmdraw.Clear(); }
/// <summary> /// 递归压缩文件夹的内部方法 /// </summary> /// <param name="folderToZip">要压缩的文件夹路径</param> /// <param name="zipStream">压缩输出流</param> /// <param name="parentFolderName">此文件夹的上级文件夹</param> /// <returns></returns> private static bool ZipDirectory(string folderToZip, ZipOutputStream zipStream, string parentFolderName) { bool result = true; string[] folders, files; ZipEntry ent = null; FileStream fs = null; Crc32 crc = new Crc32(); try { string entName = folderToZip.Replace(rootPath, string.Empty).Replace(@"\", @"/") + @"/"; //ent = new ZipEntry(entName); //zipStream.PutNextEntry(ent); //zipStream.Flush(); files = Directory.GetFiles(folderToZip); foreach (string file in files) { var ext = Path.GetExtension(file); if (!string.IsNullOrEmpty(AssetBundleMgr.instance.CompressExts.FirstOrDefault(s => s == ext))) { fs = File.OpenRead(file); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); ent = new ZipEntry(entName + Path.GetFileName(file)); ent.DateTime = DateTime.Now; ent.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); ent.Crc = crc.Value; zipStream.PutNextEntry(ent); zipStream.Write(buffer, 0, buffer.Length); } } } catch { result = false; } finally { if (fs != null) { fs.Close(); fs.Dispose(); } if (ent != null) { ent = null; } GC.Collect(); GC.Collect(1); } folders = Directory.GetDirectories(folderToZip); foreach (string folder in folders) { if (!ZipDirectory(folder, zipStream, folderToZip)) { return(false); } } return(result); }
public void Password_UnsetEncryptionAfterSetPassword_wi13909_ZOS() { // Verify that unsetting the Encryption property after // setting a Password results in no encryption being used. // This method tests ZipOutputStream. string unusedPassword = TestUtilities.GenerateRandomPassword(); int numTotalEntries = _rnd.Next(46)+653; string zipFileToCreate = "UnsetEncryption.zip"; using (FileStream fs = File.Create(zipFileToCreate)) { using (var zos = new ZipOutputStream(fs)) { zos.Password = unusedPassword; zos.Encryption = EncryptionAlgorithm.None; for (int i=0; i < numTotalEntries; i++) { if (_rnd.Next(7)==0) { string entryName = String.Format("{0:D5}/", i); zos.PutNextEntry(entryName); } else { string entryName = String.Format("{0:D5}.txt", i); zos.PutNextEntry(entryName); if (_rnd.Next(12)==0) { var block = TestUtilities.GenerateRandomAsciiString() + " "; string contentBuffer = String.Format("This is the content for entry {0}", i); int n = _rnd.Next(6) + 2; for (int j=0; j < n; j++) contentBuffer += block; byte[] buffer = System.Text.Encoding.ASCII.GetBytes(contentBuffer); zos.Write(buffer, 0, buffer.Length); } } } } } BasicVerifyZip(zipFileToCreate); }
public void Stream_64KPlusOneEntries() { const int target = 65537; var ms = new MemoryStream(); using (var s = new ZipOutputStream(ms)) { for (var i = 0; i < target; ++i) { s.PutNextEntry(new ZipEntry("dummyfile.tst")); } s.Finish(); ms.Seek(0, SeekOrigin.Begin); using (var zipFile = new ZipFile(ms)) { Assert.AreEqual(target, zipFile.Count, "Incorrect number of entries stored"); } } }