/// <summary> /// Creates a zip archive from a byte array /// </summary> /// <param name="buffer">The file in byte[] format</param> /// <param name="fileName">The name of the file you want to add to the archive</param> /// <returns></returns> public static byte[] CreateZipByteArray(byte[] buffer, string fileName) { ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32(); using (System.IO.MemoryStream zipMemoryStream = new System.IO.MemoryStream()) { ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(zipMemoryStream); zipOutputStream.SetLevel(6); ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName); zipEntry.DateTime = DateTime.Now; zipEntry.Size = buffer.Length; crc.Reset(); crc.Update(buffer); zipEntry.Crc = crc.Value; zipOutputStream.PutNextEntry(zipEntry); zipOutputStream.Write(buffer, 0, buffer.Length); zipOutputStream.Finish(); byte[] zipByteArray = new byte[zipMemoryStream.Length]; zipMemoryStream.Position = 0; zipMemoryStream.Read(zipByteArray, 0, (int)zipMemoryStream.Length); zipOutputStream.Close(); return zipByteArray; } }
/// <summary> /// Zips the specified <paramref name="baseFolder"/>. /// </summary> /// <param name="baseFolder">The folder to zip</param> /// <param name="filesToZip"> /// the files and directories within the <paramref name="baseFolder"/> to include in the zip. /// These names are only matched in the <paramref name="baseFolder"/> but not recursive. /// You can use the default globbing (* and ?). /// </param> /// <param name="filesToIgnore">Names of the files or directories to exclude from zip. Full case sensitive match. No globbing. Directories have a trailing "/".</param> public void Zip(string baseFolder, string[] filesToZip, string[] filesToIgnore) { var baseDir = new DirectoryInfo(baseFolder); foreach (var fileMask in filesToZip) { foreach (var file in baseDir.GetFiles(fileMask, SearchOption.TopDirectoryOnly)) { if (IgnoreFile(baseDir.FullName, file.FullName, filesToIgnore)) { continue; } var zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(file.Name); zipStream.PutNextEntry(zipEntry); using (var fileStream = file.OpenRead()) fileStream.CopyTo(zipStream); } foreach (var subDir in baseDir.GetDirectories(fileMask, SearchOption.TopDirectoryOnly)) { if (IgnoreFile(baseDir.FullName, subDir.FullName, filesToIgnore)) { continue; } ZipDirectory(zipStream, baseDir, subDir, filesToIgnore); } } }
/// <summary> /// 压缩 /// </summary> /// <param name="zipStream">压缩流</param> /// <param name="filePath">文件或文件夹路径</param> /// <param name="rootDirPath">根路径(就是压缩后的文件存储的路径)</param> private static void appendStream(ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream, string filePath, string fileName, string rootDirPath) { if (string.IsNullOrEmpty(filePath)) { return; } filePath = filePath.Replace('/', '\\'); if (string.IsNullOrEmpty(filePath.Replace(rootDirPath, "").Trim('\\'))) { return; } if (Directory.Exists(filePath))//若为文件夹 { DirectoryInfo dir = new DirectoryInfo(filePath); FileSystemInfo[] fileSystemList = dir.GetFileSystemInfos(); if (fileSystemList == null || fileSystemList.Length < 1) //若该文件加下面没有子文件或文件夹,需创建空的文件夹 { ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(filePath.Replace(rootDirPath, "").Trim('\\') + "\\"); //末尾“\\”用于文件夹的标记 zipStream.PutNextEntry(zipEntry); return; } foreach (FileSystemInfo fileSystem in fileSystemList) { appendStream(zipStream, fileSystem.FullName, rootDirPath); } } else if (System.IO.File.Exists(filePath)) { FileStream fs = System.IO.File.OpenRead(filePath); BinaryReader br = new BinaryReader(fs); try { FileInfo file = new FileInfo(filePath);//根据文件路径获取文件名的简便方法 ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = string.IsNullOrEmpty(fileName) ? new ICSharpCode.SharpZipLib.Zip.ZipEntry(filePath.Replace(rootDirPath, "").Trim('\\')) : new ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName); zipStream.PutNextEntry(zipEntry); //为压缩文件流提供一个容器 int packSize = 10240; int maxCount = (int)Math.Ceiling((fs.Length + 0.0) / packSize); for (int i = 0; i < maxCount; i++) { byte[] b = br.ReadBytes(packSize); //将文件流加入缓冲字节中 zipStream.Write(b, 0, b.Length); //写入字节 } } catch (Exception ex) { throw ex; } finally { br.Close(); fs.Close(); fs.Dispose(); } } }
public static void WriteFileToZip(ICSharpCode.SharpZipLib.Zip.ZipOutputStream stream, string filename, byte[] bytes) { ICSharpCode.SharpZipLib.Zip.ZipEntry ze = new ICSharpCode.SharpZipLib.Zip.ZipEntry(filename); ze.Size = bytes.Length; stream.PutNextEntry(ze); stream.Write(bytes, 0, bytes.Length); }
/// <summary> /// Zips the specified <paramref name="baseFolder"/> to the <paramref name="stream"/>. /// </summary> /// <param name="stream">Stream to write the compressed data to.</param> /// <param name="baseFolder">The folder to zip</param> /// <param name="filesToZip"> /// the files and directories within the <paramref name="baseFolder"/> to include in the zip. /// These names are only matched in the <paramref name="baseFolder"/> but not recursive. /// You can use the default globbing (* and ?). /// </param> /// <param name="filesToIgnore">Names of the files or directories to exclude from zip. Full case sensitive match. No globbing. Directories have a trailing "/".</param> public static void Zip(Stream stream, string baseFolder, string[] filesToZip, string[] filesToIgnore) { using (var s = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(stream)) { s.SetLevel(9); s.UseZip64 = ICSharpCode.SharpZipLib.Zip.UseZip64.Off; var baseDir = new DirectoryInfo(baseFolder); foreach (var fileMask in filesToZip) { foreach (var file in baseDir.GetFiles(fileMask, SearchOption.TopDirectoryOnly)) { if (IgnoreFile(baseDir.FullName, file.FullName, filesToIgnore)) continue; var zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(file.Name); s.PutNextEntry(zipEntry); using (var fileStream = file.OpenRead()) fileStream.CopyTo(s); } foreach (var subDir in baseDir.GetDirectories(fileMask, SearchOption.TopDirectoryOnly)) { if (IgnoreFile(baseDir.FullName, subDir.FullName, filesToIgnore)) continue; ZipDirectory(s, baseDir, subDir, filesToIgnore); } } s.Finish(); } }
/// <summary> /// Zip và tải xuống file nén các file /// </summary> /// <param name="serial"></param> /// <param name="listFiles"></param> /// <param name="path"></param> /// <param name="response"></param> public void DownloadMultiFiles(string serial, List <string> listFiles, string path, HttpResponse response) { string fullName = ""; string zipName = serial + ".zip"; string zipFullPath = path + zipName; ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipOut = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(System.IO.File.Create(zipFullPath)); foreach (string fileName in listFiles) { fullName = path + "\\" + fileName; System.IO.FileInfo fi = new System.IO.FileInfo(fullName); ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fi.Name); System.IO.FileStream sReader = System.IO.File.OpenRead(fullName); byte[] buff = new byte[Convert.ToInt32(sReader.Length)]; sReader.Read(buff, 0, (int)sReader.Length); entry.DateTime = fi.LastWriteTime; entry.Size = sReader.Length; sReader.Close(); zipOut.PutNextEntry(entry); zipOut.Write(buff, 0, buff.Length); } zipOut.Finish(); zipOut.Close(); DownloadSingleFile(zipName, zipFullPath, response); }
/// <summary> /// Create a zip file of the supplied file names and string data source /// </summary> /// <param name="zipPath">Output location to save the file.</param> /// <param name="filenamesAndData">File names and data in a dictionary format.</param> /// <returns>True on successfully creating the zip file.</returns> public static bool ZipData(string zipPath, Dictionary<string, string> filenamesAndData) { try { //Create our output using (var stream = new ZipOutputStream(File.Create(zipPath))) { stream.SetLevel(0); foreach (var filename in filenamesAndData.Keys) { //Create the space in the zip file: var entry = new ZipEntry(filename); var data = filenamesAndData[filename]; var bytes = Encoding.Default.GetBytes(data); stream.PutNextEntry(entry); stream.Write(bytes, 0, bytes.Length); stream.CloseEntry(); } // End For Each File. //Close stream: stream.Finish(); stream.Close(); } // End Using } catch (Exception err) { Log.Error(err); return false; } return true; }
/// <summary> /// 边打包边下载, /// </summary> /// <param name="context"></param> public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/octet-stream"; context.Response.AddHeader("Content-Disposition", "attachment;filename=Http.File.zip"); ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(context.Response.OutputStream); zipStream.SetLevel(6); string rootPath = System.Web.HttpRuntime.BinDirectory; var filePaths = System.IO.Directory.GetFiles(rootPath, "*", System.IO.SearchOption.AllDirectories); foreach (var filePath in filePaths) { string entryName = filePath.Replace(rootPath, string.Empty).TrimStart('\\'); zipStream.PutNextEntry(new ICSharpCode.SharpZipLib.Zip.ZipEntry(entryName)); using (var fs = System.IO.File.Open(filePath, System.IO.FileMode.Open)) { var bufferSize = 80 * 1024; var buffer = new byte[bufferSize]; int length = -1; while ((length = fs.Read(buffer, 0, bufferSize)) > 0) { zipStream.Write(buffer, 0, length); context.Response.Flush(); } } } zipStream.Finish(); context.Response.End(); }
/// <summary> /// Exports the query results to an excel file per query. /// </summary> /// <param name="viewType">Indicates the type of response view.</param> /// <returns></returns> public Stream ExportAsExcel(TaskItemTypes viewType) { MemoryStream ms = new MemoryStream(); var includeDataMartName = viewType != TaskItemTypes.AggregateResponse; if (Queries.Count() > 1) { var zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(ms); zipStream.IsStreamOwner = false; foreach (var grouping in Queries) { var datamartAcronym = includeDataMartName ? "-" + grouping.Select(g => g.DataMartAcronym).FirstOrDefault() : string.Empty; string zipEntryFilename = Path.ChangeExtension(CleanFilename(grouping.Key.QueryName + datamartAcronym), "xlsx"); var zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(zipEntryFilename); zipEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(zipEntry); WriteExcel(zipStream, grouping.AsEnumerable(), includeDataMartName); zipStream.CloseEntry(); } zipStream.Close(); } else { WriteExcel(ms, Queries.ElementAt(0).ToArray(), includeDataMartName); } ms.Position = 0; return(ms); }
static void Serialize(string PathName, object data, bool compressed = false) { if (compressed) { using (var s = File.Create(PathName)) { using (var gs = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(s)) { gs.PutNextEntry(new ICSharpCode.SharpZipLib.Zip.ZipEntry("data")); var bf = new BinaryFormatter(); bf.Serialize(gs, data); } } } else { using (var stream = new MemoryStream()) { var formatter = new BinaryFormatter(); formatter.Serialize(stream, data); using (var ofile = new StreamWriter(PathName)) stream.WriteTo(ofile.BaseStream); } } }
/// <summary> /// Zips all files specified to a new zip at the destination path /// </summary> public static void ZipFiles(string destination, IEnumerable <string> files) { try { using (var zipStream = new ZipOutputStream(File.Create(destination))) { var buffer = new byte[4096]; foreach (var file in files) { if (!File.Exists(file)) { Log.Trace($"ZipFiles(): File does not exist: {file}"); continue; } var entry = new ZipEntry(Path.GetFileName(file)); zipStream.PutNextEntry(entry); using (var fstream = File.OpenRead(file)) { StreamUtils.Copy(fstream, zipStream, buffer); } } } } catch (Exception err) { Log.Error(err); } }
public static byte[] Zip(this byte[] data, int level = 9) { if (data == null) { return(null); } if (data.Length == 0) { return(new byte[0]); } level = level.ToClosedInterval(0, 9); using (MemoryStream memory = new MemoryStream()) { using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream stream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(memory)) { stream.SetLevel(level); ICSharpCode.SharpZipLib.Zip.ZipEntry Entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(""); Entry.Size = data.Length; stream.PutNextEntry(Entry); stream.Write(data, 0, data.Length); } return(memory.ToArray()); } }
/// <summary> 压缩数据 </summary> public static byte[] Compress(byte[] source) { #if false//SCORPIO_UWP && !UNITY_EDITOR using (MemoryStream stream = new MemoryStream()) { System.IO.Compression.ZipArchive zipStream = new System.IO.Compression.ZipArchive(stream, System.IO.Compression.ZipArchiveMode.Create); System.IO.Compression.ZipArchiveEntry zipEntry = zipStream.CreateEntry("0.txt"); Stream entryStream = zipEntry.Open(); entryStream.Write(source, 0, source.Length); entryStream.Flush(); entryStream.Dispose(); zipStream.Dispose(); byte[] ret = stream.ToArray(); stream.Dispose(); return(ret); } #else using (MemoryStream stream = new MemoryStream()) { ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(stream); zipStream.PutNextEntry(new ICSharpCode.SharpZipLib.Zip.ZipEntry("0.txt")); zipStream.Write(source, 0, source.Length); zipStream.Finish(); byte[] ret = stream.ToArray(); zipStream.Dispose(); stream.Dispose(); return(ret); } #endif }
// *** Start programmer edit section *** (Compressor CustomMembers) /// <summary> /// Сжатие /// </summary> /// <param name="ms"></param> /// <returns></returns> public static MemoryStream Compress(MemoryStream ms) { MemoryStream restream = new MemoryStream(); ICSharpCode.SharpZipLib.Zip.ZipOutputStream s = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(restream); s.SetLevel(9); // 0 - store only to 9 - means best compression byte[] buffer = new byte[ms.Length]; ms.Seek(0, System.IO.SeekOrigin.Begin); ms.Read(buffer, 0, buffer.Length); ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("TempEntry"); s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); s.Finish(); restream.Seek(0, SeekOrigin.Begin); return(restream); }
public void ZIP(string SourcePath, string DestFile, int Compression, bool Subdir) { string[] fileList = GetFileList(SourcePath, Subdir); if (!Directory.Exists(Path.GetDirectoryName(DestFile))) { Directory.CreateDirectory(Path.GetDirectoryName(DestFile)); } FileStream fs = File.Create(DestFile); ICSharpCode.SharpZipLib.Zip.ZipOutputStream s = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(fs); s.SetLevel(Compression); foreach (string fileName in fileList) { FileStream fs2 = File.OpenRead(fileName); byte[] buffer = new byte[fs2.Length]; fs2.Read(buffer, 0, buffer.Length); fs2.Close(); ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName); s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); } s.Finish(); s.Close(); }
/// <summary> /// Constrói um pacote com as dependencias informadas. /// </summary> /// <param name="outStream">Stream de saída.</param> /// <param name="entries"></param> /// <returns></returns> public static void BuildPackage(System.IO.Stream outStream, IEnumerator <Tuple <DataEntryVersion, System.IO.Stream> > entries) { outStream.Require("outStream").NotNull(); outStream.Require("entries").NotNull(); var buffer = new byte[1024]; int read = 0; var zipOut = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(outStream); while (entries.MoveNext()) { var item = entries.Current; if (item == null) { continue; } var entryName = item.Item1.TypeName.FullName; var entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(entryName); entry.Size = item.Item2.Length; zipOut.PutNextEntry(entry); while ((read = item.Item2.Read(buffer, 0, buffer.Length)) > 0) { zipOut.Write(buffer, 0, read); } zipOut.CloseEntry(); } zipOut.Finish(); zipOut.Flush(); }
public static void Compress(Stream data, Stream outData, string fileName) { string str = ""; try { using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(outData)) { zipStream.SetLevel(3); ICSharpCode.SharpZipLib.Zip.ZipEntry newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName); newEntry.DateTime = DateTime.UtcNow; zipStream.PutNextEntry(newEntry); data.Position = 0; int size = (data.CanSeek) ? Math.Min((int)(data.Length - data.Position), 0x2000) : 0x2000; byte[] buffer = new byte[size]; int n; do { n = data.Read(buffer, 0, buffer.Length); zipStream.Write(buffer, 0, n); } while (n != 0); zipStream.CloseEntry(); zipStream.Flush(); zipStream.Close(); } } catch (Exception ex) { str = ex.Message; } }
public static MemoryStream CreateToMemoryStream(MemoryStream memStreamIn, string zipEntryName) { MemoryStream outputMemStream = new MemoryStream(); var zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(outputMemStream); zipStream.SetLevel(3); //0-9, 9 being the highest level of compression var newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(zipEntryName); newEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(newEntry); ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(memStreamIn, zipStream, new byte[4096]); zipStream.CloseEntry(); zipStream.IsStreamOwner = false; // False stops the Close also Closing the underlying stream. zipStream.Close(); // Must finish the ZipOutputStream before using outputMemStream. outputMemStream.Position = 0; return(outputMemStream); // Alternative outputs: // ToArray is the cleaner and easiest to use correctly with the penalty of duplicating allocated memory. //byte[] byteArrayOut = outputMemStream.ToArray(); // GetBuffer returns a raw buffer raw and so you need to account for the true length yourself. //byte[] byteArrayOut = outputMemStream.GetBuffer(); //long len = outputMemStream.Length; }
/// <summary> /// Compresses the specified source file. /// </summary> /// <param name="source">The source file to be compressed</param> /// <param name="destination">The destination zip file path</param> /// <param name="zipEntryName">The zip entry name for the file</param> /// <param name="deleteOriginal">True to delete the source file upon completion</param> public static void Zip(string source, string destination, string zipEntryName, bool deleteOriginal) { try { var buffer = new byte[4096]; using (var stream = new ZipOutputStream(File.Create(destination))) { //Zip the text file. var entry = new ZipEntry(zipEntryName); stream.PutNextEntry(entry); using (var fs = File.OpenRead(source)) { int sourceBytes; do { sourceBytes = fs.Read(buffer, 0, buffer.Length); stream.Write(buffer, 0, sourceBytes); }while (sourceBytes > 0); } } //Delete the old text file: if (deleteOriginal) { File.Delete(source); } } catch (Exception err) { Log.Error(err); } }
/// <summary> /// Create a zip file of the supplied file names and string data source /// </summary> /// <param name="zipPath">Output location to save the file.</param> /// <param name="filenamesAndData">File names and data in a dictionary format.</param> /// <returns>True on successfully creating the zip file.</returns> public static bool ZipData(string zipPath, Dictionary <string, string> filenamesAndData) { try { //Create our output using (var stream = new ZipOutputStream(File.Create(zipPath))) { foreach (var filename in filenamesAndData.Keys) { //Create the space in the zip file: var entry = new ZipEntry(filename); var data = filenamesAndData[filename]; var bytes = Encoding.Default.GetBytes(data); stream.PutNextEntry(entry); stream.Write(bytes, 0, bytes.Length); stream.CloseEntry(); } // End For Each File. //Close stream: stream.Finish(); stream.Close(); } // End Using } catch (Exception err) { Log.Error(err); return(false); } return(true); }
void AddFilesToZip(ITaskItem [] files, ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream) { if (files == null) { return; } foreach (ITaskItem item in files) { string target_path = item.GetMetadata("TargetPath"); if (String.IsNullOrEmpty(target_path)) { target_path = Path.GetFileName(item.ItemSpec); } zipStream.PutNextEntry(new ICSharpCode.SharpZipLib.Zip.ZipEntry(target_path)); using (FileStream inStream = File.OpenRead(item.ItemSpec)) { int readCount; byte[] buffer = new byte[4096]; do { readCount = inStream.Read(buffer, 0, buffer.Length); zipStream.Write(buffer, 0, readCount); } while (readCount > 0); } } }
/// <summary> /// Zips the specified <paramref name="baseFolder"/> to the <paramref name="stream"/>. /// </summary> /// <param name="stream">Stream to write the compressed data to.</param> /// <param name="baseFolder">The folder to zip</param> /// <param name="filesToZip"> /// the files and directories within the <paramref name="baseFolder"/> to include in the zip. /// These names are only matched in the <paramref name="baseFolder"/> but not recursive. /// You can use the default globbing (* and ?). /// </param> /// <param name="filesToIgnore">Names of the files or directories to exclude from zip. Full case sensitive match. No globbing. Directories have a trailing "/".</param> public static void Zip(Stream stream, string baseFolder, string[] filesToZip, string[] filesToIgnore) { using (var s = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(stream)) { s.SetLevel(9); s.UseZip64 = ICSharpCode.SharpZipLib.Zip.UseZip64.Off; var baseDir = new DirectoryInfo(baseFolder); foreach (var fileMask in filesToZip) { foreach (var file in baseDir.GetFiles(fileMask, SearchOption.TopDirectoryOnly)) { if (IgnoreFile(baseDir.FullName, file.FullName, filesToIgnore)) { continue; } var zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(file.Name); s.PutNextEntry(zipEntry); using (var fileStream = file.OpenRead()) fileStream.CopyTo(s); } foreach (var subDir in baseDir.GetDirectories(fileMask, SearchOption.TopDirectoryOnly)) { if (IgnoreFile(baseDir.FullName, subDir.FullName, filesToIgnore)) { continue; } ZipDirectory(s, baseDir, subDir, filesToIgnore); } } s.Finish(); } }
/// <summary> /// Performs an in memory zip of the specified bytes /// </summary> /// <param name="bytes">The file contents in bytes to be zipped</param> /// <param name="zipEntryName">The zip entry name</param> /// <returns>The zipped file as a byte array</returns> public static byte[] ZipBytes(byte[] bytes, string zipEntryName) { using (var memoryStream = new MemoryStream()) using (var stream = new ZipOutputStream(memoryStream)) { var entry = new ZipEntry(zipEntryName); stream.PutNextEntry(entry); var buffer = new byte[16 * 1024]; StreamUtils.Copy(new MemoryStream(bytes), stream, buffer); return(memoryStream.GetBuffer()); } }
/// <summary> /// Exports the responses in csv format, if the response is multi-query each query response will be a separate csv file zipped into a file of the request name. /// </summary> /// <param name="viewType">The response result view type, Individual or Aggregate.</param> /// <returns></returns> public Stream ExportAsCSV(TaskItemTypes viewType) { var queries = Queries.ToArray(); var includeDataMartName = viewType != TaskItemTypes.AggregateResponse; MemoryStream ms = new MemoryStream(); if (queries.Count() > 1) { var zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(ms); zipStream.IsStreamOwner = false; foreach (var grouping in Queries) { var datamartAcronym = includeDataMartName ? "-" + grouping.Select(g => g.DataMartAcronym).FirstOrDefault() : string.Empty; string zipEntryFilename = Path.ChangeExtension(CleanFilename(grouping.Key.QueryName + datamartAcronym), "csv"); var zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(zipEntryFilename); zipEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(zipEntry); using (var writer = new StreamWriter(zipStream, System.Text.Encoding.Default, 1024, true)) { for (int i = 0; i < grouping.Count(); i++) { var responseResult = grouping.ElementAt(i); WriteCSV(writer, responseResult, i == 0, includeDataMartName); } writer.Flush(); zipStream.CloseEntry(); } } zipStream.Close(); } else { var firstQueryGrouping = Queries.ElementAt(0).ToArray(); using (var writer = new StreamWriter(ms, System.Text.Encoding.Default, 1024, true)) { for (int i = 0; i < firstQueryGrouping.Length; i++) { WriteCSV(writer, firstQueryGrouping[i], i == 0, includeDataMartName); } writer.Flush(); } } ms.Position = 0; return(ms); }
public static MemoryStream CompressStream(MemoryStream stream, string entryname) { MemoryStream ms = new MemoryStream(); using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipstream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(ms)) { ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(entryname); entry.DateTime = DateTime.Now; zipstream.PutNextEntry(entry); zipstream.Write(stream.ToArray(), 0, (int)stream.Length); zipstream.Flush(); zipstream.Finish(); zipstream.Close(); } return(ms); }
public static void ZipFile(System.Collections.Generic.List <string> filesToZip, string outFile, int compression = 3, bool IsMapPath = true) { outFile = IsMapPath ? TM.Core.IO.MapPath(outFile) : outFile; if (compression < 0 || compression > 9) { throw new ArgumentException("Invalid compression rate (just 0-9)."); } if (!Directory.Exists(new FileInfo(outFile).Directory.ToString())) { throw new ArgumentException("The Path does not exist."); } foreach (string c in filesToZip) { if (!File.Exists(IsMapPath ? TM.Core.IO.MapPath(c) : c)) { throw new ArgumentException(string.Format("The File {0} does not exist!", c)); } } var crc32 = new ICSharpCode.SharpZipLib.Checksum.Crc32(); var stream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(File.Create(outFile)); stream.SetLevel(compression); for (int i = 0; i < filesToZip.Count; i++) { var entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(Path.GetFileName(filesToZip[i])); entry.DateTime = DateTime.Now; var _filesToZip = IsMapPath ? TM.Core.IO.MapPath(filesToZip[i]) : filesToZip[i]; using (FileStream fs = File.OpenRead(_filesToZip)) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); entry.Size = fs.Length; fs.Close(); crc32.Reset(); crc32.Update(buffer); entry.Crc = crc32.Value; stream.PutNextEntry(entry); stream.Write(buffer, 0, buffer.Length); } } stream.Finish(); stream.Close(); }
private void DownloadZip(HttpContext context, List <Fe> lstfe) { //找出所有文件记录,2种可能情况, //1,按文件id, var lstfileId = lstfe.Where(x => x.cc == "file").Select(x => x.id).Distinct().ToList(); var lstFileEntity1 = this.dbcontext.FileEntity.Where(x => x.UploadStepValue == Model.UploadStep.完成).Where(x => lstfileId.Contains(x.Id)).ToList(); //2,按父目录 var lstdir = lstfe.Where(x => x.cc == "dir").Select(x => x.path).Distinct().ToList(); var lstdir2 = lstdir.Select(x => x + "\\").ToList(); var lstFileEntity2 = lstdir2.Select(x => this.dbcontext.FileEntity.Where(a => a.UploadStepValue == Model.UploadStep.完成).Where(a => a.FullName.StartsWith(x)).ToList()) .SelectMany(x => x) .ToList(); lstFileEntity1.AddRange(lstFileEntity2); var lstFileEntity = lstFileEntity1.GroupBy(x => x.Id).Select(gp => gp.First()).ToList(); context.Response.ContentType = "application/octet-stream"; string rpath = context.Request["rpath"] ?? string.Empty; string bundleName = rpath == string.Empty ? "root" : System.IO.Path.GetFileName(rpath); context.Response.AddHeader("Content-Disposition", "attachment;filename*=utf-8'zh_cn'" + context.Server.UrlEncode(bundleName + "-bundle.zip")); ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(context.Response.OutputStream); zipStream.SetLevel(6); string rootPath = this.GetRootFolder(context); string basepath = System.IO.Path.Combine(rootPath, rpath); var filePaths = lstFileEntity.Select(x => System.IO.Path.Combine(rootPath, x.FullName)).ToList(); foreach (var filePath in filePaths) { string entryName = filePath.Replace(basepath, string.Empty).TrimStart('\\'); zipStream.PutNextEntry(new ICSharpCode.SharpZipLib.Zip.ZipEntry(entryName)); using (var fs = System.IO.File.Open(filePath, System.IO.FileMode.Open)) { var bufferSize = 1 * 1024 / 2; var buffer = new byte[bufferSize]; int length = -1; while ((length = fs.Read(buffer, 0, bufferSize)) > 0) { zipStream.Write(buffer, 0, length); context.Response.Flush(); } } } zipStream.Finish(); }
private void Compress(Stream data, Stream outData) { string str = ""; try { using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(outData)) { zipStream.SetLevel(3); ICSharpCode.SharpZipLib.Zip.ZipEntry newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("data.xml"); newEntry.DateTime = DateTime.UtcNow; //newEntry.Size = data.Length; zipStream.PutNextEntry(newEntry); //data.CopyTo(zipStream); //CopyStream(data, zipStream); //zipStream.Write(data, 0, data.Length); // zipStream.Finish(); //zipStream.Close();//? //byte[] buffer = new byte[32768]; //int read; //while ((read = data.Read(buffer, 0, buffer.Length)) > 0) //{ // zipStream.Write(buffer, 0, read); //} data.Position = 0; int size = (data.CanSeek) ? Math.Min((int)(data.Length - data.Position), 0x2000) : 0x2000; byte[] buffer = new byte[size]; int n; do { n = data.Read(buffer, 0, buffer.Length); zipStream.Write(buffer, 0, n); } while (n != 0); zipStream.CloseEntry(); zipStream.Flush(); zipStream.Close(); } } catch (Exception ex) { str = ex.Message; } }
public static void Zip(string data, string zipPath, string zipEntry) { using (var stream = new ZipOutputStream(File.Create(zipPath))) { var entry = new ZipEntry(zipEntry); stream.PutNextEntry(entry); var buffer = new byte[4096]; using (var dataReader = new MemoryStream(Encoding.Default.GetBytes(data))) { int sourceBytes; do { sourceBytes = dataReader.Read(buffer, 0, buffer.Length); stream.Write(buffer, 0, sourceBytes); }while (sourceBytes > 0); } } }
public static void DownloadZipToBrowser(System.Collections.Generic.List <string> zipFileList) { System.Web.HttpContext.Current.Response.ContentType = "application/zip"; // If the browser is receiving a mangled zipfile, IIS Compression may cause this problem. Some members have found that //Response.ContentType = "application/octet-stream" has solved this. May be specific to Internet Explorer. System.Web.HttpContext.Current.Response.AppendHeader("content-disposition", "attachment; filename=\"Download.zip\""); System.Web.HttpContext.Current.Response.CacheControl = "Private"; System.Web.HttpContext.Current.Response.Cache.SetExpires(DateTime.Now.AddMinutes(5)); // or put a timestamp in the filename in the content-disposition byte[] buffer = new byte[4096]; var zipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(System.Web.HttpContext.Current.Response.OutputStream); zipOutputStream.SetLevel(3); //0-9, 9 being the highest level of compression foreach (string fileName in zipFileList) { Stream fs = File.OpenRead(TM.IO.FileDirectory.MapPath(fileName)); // or any suitable inputstream var entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(ICSharpCode.SharpZipLib.Zip.ZipEntry.CleanName(fileName)); entry.Size = fs.Length; // Setting the Size provides WinXP built-in extractor compatibility, // but if not available, you can set zipOutputStream.UseZip64 = UseZip64.Off instead. zipOutputStream.PutNextEntry(entry); int count = fs.Read(buffer, 0, buffer.Length); while (count > 0) { zipOutputStream.Write(buffer, 0, count); count = fs.Read(buffer, 0, buffer.Length); if (!System.Web.HttpContext.Current.Response.IsClientConnected) { break; } System.Web.HttpContext.Current.Response.Flush(); } fs.Close(); } zipOutputStream.Close(); System.Web.HttpContext.Current.Response.Flush(); System.Web.HttpContext.Current.Response.End(); }
// public static byte[] Compress(byte[] data, string fileName) { // Compress using (MemoryStream fsOut = new MemoryStream()) { using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(fsOut)) { zipStream.SetLevel(3); ICSharpCode.SharpZipLib.Zip.ZipEntry newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName); newEntry.DateTime = DateTime.UtcNow; newEntry.Size = data.Length; zipStream.PutNextEntry(newEntry); zipStream.Write(data, 0, data.Length); zipStream.Finish(); zipStream.Close(); } return(fsOut.ToArray()); } }
/// <summary> /// Create a zip file of the supplied file names and string data source /// </summary> /// <param name="zipPath">Output location to save the file.</param> /// <param name="filenamesAndData">File names and data in a dictionary format.</param> /// <returns>True on successfully creating the zip file.</returns> public static bool ZipData(string zipPath, Dictionary<string, string> filenamesAndData) { var success = true; var buffer = new byte[4096]; try { //Create our output using (var stream = new ZipOutputStream(File.Create(zipPath))) { foreach (var filename in filenamesAndData.Keys) { //Create the space in the zip file: var entry = new ZipEntry(filename); //Get a Byte[] of the file data: var file = Encoding.Default.GetBytes(filenamesAndData[filename]); stream.PutNextEntry(entry); using (var ms = new MemoryStream(file)) { int sourceBytes; do { sourceBytes = ms.Read(buffer, 0, buffer.Length); stream.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } } // End For Each File. //Close stream: stream.Finish(); stream.Close(); } // End Using } catch (Exception err) { Log.Error(err); success = false; } return success; }
public static byte[] CompressFile(byte[] data, string filename) { Stream stream = new MemoryStream(data); // Compress using (MemoryStream fsOut = new MemoryStream()) { using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(fsOut)) { zipStream.SetLevel(3); ICSharpCode.SharpZipLib.Zip.ZipEntry newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(filename); newEntry.DateTime = DateTime.UtcNow; zipStream.PutNextEntry(newEntry); StreamUtils.Copy(stream, zipStream, new byte[2048]); zipStream.Finish(); zipStream.Close(); } return(fsOut.ToArray()); } }
public static void Compress2(Stream data, Stream outData, string fileName) { string str = ""; try { using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(outData)) { zipStream.SetLevel(3); ICSharpCode.SharpZipLib.Zip.ZipEntry newEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName); newEntry.DateTime = DateTime.UtcNow; zipStream.PutNextEntry(newEntry); data.CopyTo(zipStream); } } catch (Exception ex) { str = ex.Message; } }
BuildResult Zip (IProgressMonitor monitor, MoonlightProject proj, DotNetProjectConfiguration conf, ConfigurationSelector slnConf) { var xapName = GetXapName (proj, conf); var src = new List<string> (); var targ = new List<string> (); src.Add (conf.CompiledOutputName); targ.Add (conf.CompiledOutputName.FileName); // FIXME: this is a hack for the Mono Soft Debugger. In future the mdb files should be *beside* the xap, // when sdb supports that model. Note that there's no point doing this for pdb files, because the debuggers // that read pdb files don't expect them to be in the xap. var doSdbCopy = conf.DebugMode && proj.TargetRuntime is MonoDevelop.Core.Assemblies.MonoTargetRuntime; if (doSdbCopy) { FilePath mdb = conf.CompiledOutputName + ".mdb"; if (File.Exists (mdb)) { src.Add (mdb); targ.Add (mdb.FileName); } } if (proj.GenerateSilverlightManifest) { src.Add (conf.OutputDirectory.Combine ("AppManifest.xaml")); targ.Add ("AppManifest.xaml"); } foreach (ProjectFile pf in proj.Files) { if (pf.BuildAction == BuildAction.Content) { src.Add (pf.FilePath); targ.Add (pf.ProjectVirtualPath); } } BuildResult res = new BuildResult (); // The "copy to output" files don't seem to be included in xaps, so we can't use project.GetSupportFiles. // Instead we need to iterate over the refs and handle them manually. foreach (ProjectReference pr in proj.References) { if (pr.LocalCopy) { var pk = pr.Package; if (pk == null || !pk.IsFrameworkPackage || pk.Name.EndsWith ("-redist")) { string err = pr.ValidationErrorMessage; if (!String.IsNullOrEmpty (err)) { string msg = String.Format ("Could not add reference '{0}' to '{1}': {2}", pr.Reference, xapName.FileName, err); res.AddError (msg); monitor.Log.WriteLine (msg); continue; } foreach (string s in pr.GetReferencedFileNames (slnConf)) { src.Add (s); targ.Add (Path.GetFileName (s)); if (doSdbCopy && s.EndsWith (".dll")) { FilePath mdb = s + ".mdb"; if (File.Exists (mdb)) { src.Add (mdb); targ.Add (mdb.FileName); } } } } } } if (res.ErrorCount > 0) { res.FailedBuildCount++; return res; } if (File.Exists (xapName)) { DateTime lastMod = File.GetLastWriteTime (xapName); bool needsWrite = false; foreach (string file in src) { if (File.GetLastWriteTime (file) > lastMod) { needsWrite = true; break; } } if (!needsWrite) return null; } monitor.Log.WriteLine ("Compressing XAP file..."); try { using (FileStream fs = new FileStream (xapName, FileMode.Create)) { var zipfile = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream (fs); zipfile.SetLevel (9); byte[] buffer = new byte[4096]; for (int i = 0; i < src.Count && !monitor.IsCancelRequested; i++) { zipfile.PutNextEntry (new ICSharpCode.SharpZipLib.Zip.ZipEntry (targ[i])); using (FileStream inStream = File.OpenRead (src[i])) { int readCount; do { readCount = inStream.Read (buffer, 0, buffer.Length); zipfile.Write (buffer, 0, readCount); } while (readCount > 0); } } if (!monitor.IsCancelRequested) { zipfile.Finish (); zipfile.Close (); } } } catch (IOException ex) { monitor.ReportError ("Error writing xap file.", ex); res.AddError ("Error writing xap file:" + ex.ToString ()); res.FailedBuildCount++; try { if (File.Exists (xapName)) File.Delete (xapName); } catch {} return res; } if (monitor.IsCancelRequested) { try { if (File.Exists (xapName)) File.Delete (xapName); } catch {} } return res; }
protected virtual void SerializeHeightmap(Map map, Stream stream) { // Heightmap serialization method 3 var i = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(stream); var entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry("Heightmap"); i.PutNextEntry(entry); var bw = new BinaryWriter(i); bw.Write(map.Ground.Heightmap.GetLength(0)); bw.Write(map.Ground.Heightmap.GetLength(1)); for (var y = 0; y < map.Ground.Heightmap.GetLength(0); y++) for (var x = 0; x < map.Ground.Heightmap.GetLength(1); x++) bw.Write(map.Ground.Heightmap[y, x].R); i.Close(); }
/// <summary> /// Performs an in memory zip of the specified bytes /// </summary> /// <param name="bytes">The file contents in bytes to be zipped</param> /// <param name="zipEntryName">The zip entry name</param> /// <returns>The zipped file as a byte array</returns> public static byte[] ZipBytes(byte[] bytes, string zipEntryName) { using (var memoryStream = new MemoryStream()) using (var stream = new ZipOutputStream(memoryStream)) { var entry = new ZipEntry(zipEntryName); stream.PutNextEntry(entry); var buffer = new byte[16*1024]; StreamUtils.Copy(new MemoryStream(bytes), stream, buffer); return memoryStream.GetBuffer(); } }
internal void AddResources(Dictionary<string, List<ResourceItem>> resources, bool compressedResources) { Tracer.Info(Tracer.Compiler, "CompilerClassLoader adding resources..."); // BUG we need to call GetTypeWrapperFactory() to make sure that the assemblyBuilder is created (when building an empty target) ModuleBuilder moduleBuilder = this.GetTypeWrapperFactory().ModuleBuilder; Dictionary<string, Dictionary<string, ResourceItem>> jars = new Dictionary<string, Dictionary<string, ResourceItem>>(); foreach (KeyValuePair<string, List<ResourceItem>> kv in resources) { foreach (ResourceItem item in kv.Value) { int count = 0; string jarName = item.jar; retry: Dictionary<string, ResourceItem> jar; if (!jars.TryGetValue(jarName, out jar)) { jar = new Dictionary<string, ResourceItem>(); jars.Add(jarName, jar); } if (jar.ContainsKey(kv.Key)) { jarName = Path.GetFileNameWithoutExtension(item.jar) + "-" + (count++) + Path.GetExtension(item.jar); goto retry; } jar.Add(kv.Key, item); } } foreach (KeyValuePair<string, Dictionary<string, ResourceItem>> jar in jars) { MemoryStream mem = new MemoryStream(); using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zip = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(mem)) { foreach (KeyValuePair<string, ResourceItem> kv in jar.Value) { ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(kv.Key); if (kv.Value.zipEntry == null) { zipEntry.CompressionMethod = ICSharpCode.SharpZipLib.Zip.CompressionMethod.Stored; } else { zipEntry.Comment = kv.Value.zipEntry.Comment; zipEntry.CompressionMethod = kv.Value.zipEntry.CompressionMethod; zipEntry.DosTime = kv.Value.zipEntry.DosTime; zipEntry.ExternalFileAttributes = kv.Value.zipEntry.ExternalFileAttributes; zipEntry.ExtraData = kv.Value.zipEntry.ExtraData; zipEntry.Flags = kv.Value.zipEntry.Flags; } if (compressedResources || zipEntry.CompressionMethod != ICSharpCode.SharpZipLib.Zip.CompressionMethod.Stored) { zip.SetLevel(9); zipEntry.CompressionMethod = ICSharpCode.SharpZipLib.Zip.CompressionMethod.Deflated; } zip.PutNextEntry(zipEntry); if (kv.Value.data != null) { zip.Write(kv.Value.data, 0, kv.Value.data.Length); } zip.CloseEntry(); } } mem = new MemoryStream(mem.ToArray()); string name = jar.Key; if (options.targetIsModule) { name = Path.GetFileNameWithoutExtension(name) + "-" + moduleBuilder.ModuleVersionId.ToString("N") + Path.GetExtension(name); } jarList.Add(name); moduleBuilder.DefineManifestResource(name, mem, ResourceAttributes.Public); } }
/// <summary> /// Zips all files specified to a new zip at the destination path /// </summary> public static void ZipFiles(string destination, IEnumerable<string> files) { try { using (var zipStream = new ZipOutputStream(File.Create(destination))) { var buffer = new byte[4096]; foreach (var file in files) { if (!File.Exists(file)) { Log.Trace("ZipFiles(): File does not exist: " + file); continue; } var entry = new ZipEntry(Path.GetFileName(file)); zipStream.PutNextEntry(entry); using (var fstream = File.OpenRead(file)) { StreamUtils.Copy(fstream, zipStream, buffer); } } } } catch (Exception err) { Log.Error(err); } }
/// <summary> /// Zips the specified lines of text into the zipPath /// </summary> /// <param name="zipPath">The destination zip file path</param> /// <param name="zipEntry">The entry name in the zip</param> /// <param name="lines">The lines to be written to the zip</param> /// <returns>True if successful, otherwise false</returns> public static bool ZipData(string zipPath, string zipEntry, IEnumerable<string> lines) { try { using (var stream = new ZipOutputStream(File.Create(zipPath))) using (var writer = new StreamWriter(stream)) { var entry = new ZipEntry(zipEntry); stream.PutNextEntry(entry); foreach (var line in lines) { writer.WriteLine(line); } } return true; } catch (Exception err) { Log.Error(err); return false; } }
/// <summary> /// Create a zip file of the supplied file names and data using a byte array /// </summary> /// <param name="zipPath">Output location to save the file.</param> /// <param name="filenamesAndData">File names and data in a dictionary format.</param> /// <returns>True on successfully saving the file</returns> public static bool ZipData(string zipPath, IEnumerable<KeyValuePair<string, byte[]>> filenamesAndData) { var success = true; var buffer = new byte[4096]; try { //Create our output using (var stream = new ZipOutputStream(File.Create(zipPath))) { foreach (var file in filenamesAndData) { //Create the space in the zip file: var entry = new ZipEntry(file.Key); //Get a Byte[] of the file data: stream.PutNextEntry(entry); using (var ms = new MemoryStream(file.Value)) { int sourceBytes; do { sourceBytes = ms.Read(buffer, 0, buffer.Length); stream.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } } // End For Each File. //Close stream: stream.Finish(); stream.Close(); } // End Using } catch (Exception err) { Log.Error("QC.Data.ZipData(): " + err.Message); success = false; } return success; }
public static void Zip(string data, string zipPath, string zipEntry) { using (var stream = new ZipOutputStream(File.Create(zipPath))) { var entry = new ZipEntry(zipEntry); stream.PutNextEntry(entry); var buffer = new byte[4096]; using (var dataReader = new MemoryStream(Encoding.Default.GetBytes(data))) { int sourceBytes; do { sourceBytes = dataReader.Read(buffer, 0, buffer.Length); stream.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } } }
/// <summary> /// Compress a given file and delete the original file. Automatically rename the file to name.zip. /// </summary> /// <param name="textPath">Path of the original file</param> /// <param name="deleteOriginal">Boolean flag to delete the original file after completion</param> /// <returns>String path for the new zip file</returns> public static string Zip(string textPath, bool deleteOriginal = true) { var zipPath = ""; try { var buffer = new byte[4096]; zipPath = textPath.Replace(".csv", ".zip"); zipPath = zipPath.Replace(".txt", ".zip"); //Open the zip: using (var stream = new ZipOutputStream(File.Create(zipPath))) { //Zip the text file. var entry = new ZipEntry(Path.GetFileName(textPath)); stream.PutNextEntry(entry); using (var fs = File.OpenRead(textPath)) { int sourceBytes; do { sourceBytes = fs.Read(buffer, 0, buffer.Length); stream.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } //Close stream: stream.Finish(); stream.Close(); } //Delete the old text file: if (deleteOriginal) File.Delete(textPath); } catch (Exception err) { Log.Error("QC.Data.Zip(): " + err.Message); } return zipPath; }
private void menuExportTeamData_Click(object sender, EventArgs e) { SaveFileDialog d = new SaveFileDialog(); d.AddExtension = true; d.DefaultExt = ".zip"; d.Filter = T("Tutti i file ZIP (*.zip)")+"|*.zip"; d.FileName = "RMO-Team-Data-" + DateTime.Now.ToString("yyyy-MM-dd") + ".zip"; d.InitialDirectory = My.Dir.Desktop; d.OverwritePrompt = true; d.Title = T("Nome del file da esportare"); if (d.ShowDialog() == DialogResult.OK) { try { string[] filenames = System.IO.Directory.GetFiles(PATH_HISTORY, "*.team"); progressBar.Value = 0; progressBar.Maximum = filenames.Length; using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream s = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(System.IO.File.Create(d.FileName))) { s.SetLevel(9); byte[] buffer = new byte[4096]; foreach (string file in filenames) { ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(System.IO.Path.GetFileName(file)); entry.DateTime = DateTime.Now; s.PutNextEntry(entry); using (System.IO.FileStream fs = System.IO.File.OpenRead(file)) { int sourceBytes; do { sourceBytes = fs.Read(buffer, 0, buffer.Length); s.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } progressBar.Value++; } s.Finish(); s.Close(); lStatus.Text = T("Esportazione del backup ultimata correttamente!"); } } catch (Exception ex) { My.Box.Errore(T("Errore durante l'esportazione del backup")+"\r\n"+ex.Message); } progressBar.Value = 0; } }
public void ZipAdminFile(string strFile, List<string> filesExtra) { if (File.Exists(strFile)) { if (GetConfig().ZipAfterIndexed == true) { try { string zipFilePath = Path.ChangeExtension(strFile, ".zip"); if (File.Exists(zipFilePath)) File.Delete(zipFilePath); if (filesExtra == null) { filesExtra = new List<string>(); } if (strFile != null) { filesExtra.Add(strFile); } ICSharpCode.SharpZipLib.Zip.ZipOutputStream strmZipOutputStream = default(ICSharpCode.SharpZipLib.Zip.ZipOutputStream); strmZipOutputStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(File.Create(zipFilePath)); if (GetConfig().CollapseFolders) { // minus.gif string f1 = Application.StartupPath + Path.DirectorySeparatorChar + "plus.gif"; if (File.Exists(f1)) filesExtra.Add(f1); string f2 = Application.StartupPath + Path.DirectorySeparatorChar + "minus.gif"; if (File.Exists(f2)) filesExtra.Add(f2); } if (File.Exists(GetConfig().LogoPath)) { filesExtra.Add(GetConfig().LogoPath); } foreach (string filePath in filesExtra) { FileStream strmFile = File.OpenRead(filePath); byte[] abyBuffer = new byte[(int)strmFile.Length - 1 + 1]; strmFile.Read(abyBuffer, 0, abyBuffer.Length); ICSharpCode.SharpZipLib.Zip.ZipEntry objZipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(Path.GetFileName(filePath)); objZipEntry.DateTime = DateTime.Now; objZipEntry.Size = strmFile.Length; strmFile.Close(); strmZipOutputStream.PutNextEntry(objZipEntry); strmZipOutputStream.Write(abyBuffer, 0, abyBuffer.Length); } ///''''''''''''''''''''''''''''''''' // Finally Close strmZipOutputStream ///''''''''''''''''''''''''''''''''' strmZipOutputStream.Finish(); strmZipOutputStream.Close(); if (GetConfig().ZipAndDeleteFile == true) { File.Delete(strFile); } } catch (System.UnauthorizedAccessException ex) { Debug.WriteLine(ex.ToString()); } } } }