/// <summary> /// Zips a string into a zipped byte array. /// </summary> /// <param name="textToZip">The text to be zipped.</param> /// <returns>byte[] representing a zipped stream</returns> public static void ZipUsingDotNetZip(string json, string yaml, string filePath) { using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) { zip.AddEntry("Superheroes.json", json); zip.AddEntry("Superheroes.yaml", yaml); zip.Save(filePath); } }
/// <summary> /// Generates a FileStreamResult containing a zip file with the EXCEL file in it /// </summary> /// <typeparam name="T">Type of object in the object list parameter</typeparam> /// <param name="objectList">The object list enumerable. This contains the data for the EXCEL file</param> /// <param name="fileName">The file name of the EXCEL</param> /// <returns>FileStreamResult</returns> public FileContentResult CreateZipFileFileContentResult <T>(IEnumerable <T> objectList, string fileName) { var contentType = System.Net.Mime.MediaTypeNames.Application.Zip; using (var memoryStream = new System.IO.MemoryStream()) { using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) { using (var package = new OfficeOpenXml.ExcelPackage()) { var workSheet1 = package.Workbook.Worksheets.Add("Sheet1"); workSheet1.Cells["A1"].LoadFromCollection <T>(objectList, true); var firstRow = workSheet1.Row(1); if (firstRow != null) { firstRow.Style.Font.Bold = true; } zip.AddEntry(fileName, package.GetAsByteArray()); zip.Save(memoryStream); var fcr = new FileContentResult(memoryStream.ToArray(), contentType); //NOTE: Using a File Stream Result will not work. fcr.FileDownloadName = fileName + ".zip"; return(fcr); } } } }
public void ShortNamesJsonSerialization_NormalAndZip_DotNetZip_EncodingMethod() { List <GPSPoint2> points = new List <GPSPoint2>(); Random rand = new Random(); for (int i = 0; i < 1000; i++) { points.Add(new GPSPoint2((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), DateTime.Now)); } string output = JsonConvert.SerializeObject(points); var bytes = UTF8Encoding.UTF8.GetBytes(output); var length1 = bytes.Length; byte[] compressedData; using (MemoryStream str = new MemoryStream()) { using (var zip = new Ionic.Zip.ZipFile()) { zip.CompressionLevel = CompressionLevel.BestCompression; zip.AddEntry("README.txt", bytes); zip.Save(str); } var r = str.Length; compressedData = str.ToArray(); } }
public static byte[] SerializeVoxelAreaData(VoxelArea v) { #if !ASTAR_RECAST_CLASS_BASED_LINKED_LIST System.IO.MemoryStream stream = new System.IO.MemoryStream(); System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream); writer.Write (v.width); writer.Write (v.depth); writer.Write (v.linkedSpans.Length); for (int i=0;i<v.linkedSpans.Length;i++) { writer.Write(v.linkedSpans[i].area); writer.Write(v.linkedSpans[i].bottom); writer.Write(v.linkedSpans[i].next); writer.Write(v.linkedSpans[i].top); } //writer.Close(); writer.Flush(); Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(); stream.Position = 0; zip.AddEntry ("data",stream); System.IO.MemoryStream stream2 = new System.IO.MemoryStream(); zip.Save(stream2); byte[] bytes = stream2.ToArray(); stream.Close(); stream2.Close(); return bytes; #else throw new System.NotImplementedException ("This method only works with !ASTAR_RECAST_CLASS_BASED_LINKED_LIST"); #endif }
public static byte[] SerializeVoxelAreaData(VoxelArea v) { System.IO.MemoryStream stream = new System.IO.MemoryStream(); System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream); writer.Write(v.width); writer.Write(v.depth); writer.Write(v.linkedSpans.Length); for (int i = 0; i < v.linkedSpans.Length; i++) { writer.Write(v.linkedSpans[i].area); writer.Write(v.linkedSpans[i].bottom); writer.Write(v.linkedSpans[i].next); writer.Write(v.linkedSpans[i].top); } //writer.Close(); writer.Flush(); Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(); stream.Position = 0; zip.AddEntry("data", stream); System.IO.MemoryStream stream2 = new System.IO.MemoryStream(); zip.Save(stream2); byte[] bytes = stream2.ToArray(); stream.Close(); stream2.Close(); return(bytes); }
/// <summary> /// Append the zip data to the file-entry specified. /// </summary> /// <param name="path"></param> /// <param name="entry"></param> /// <param name="data"></param> /// <returns></returns> public static bool ZipCreateAppendData(string path, string entry, string data) { try { if (File.Exists(path)) { using (var zip = ZipFile.Read(path)) { zip.AddEntry(entry, data); zip.Save(); } } else { using (var zip = new ZipFile(path)) { zip.AddEntry(entry, data); zip.Save(); } } } catch (Exception err) { Log.Error(err); return(false); } return(true); }
public static byte[] SerializeVoxelAreaData (VoxelArea v) { #if !ASTAR_RECAST_CLASS_BASED_LINKED_LIST System.IO.MemoryStream stream = new System.IO.MemoryStream(); System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream); writer.Write (v.width); writer.Write (v.depth); writer.Write (v.linkedSpans.Length); for (int i=0;i<v.linkedSpans.Length;i++) { writer.Write(v.linkedSpans[i].area); writer.Write(v.linkedSpans[i].bottom); writer.Write(v.linkedSpans[i].next); writer.Write(v.linkedSpans[i].top); } //writer.Close(); writer.Flush(); Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(); stream.Position = 0; zip.AddEntry ("data",stream); System.IO.MemoryStream stream2 = new System.IO.MemoryStream(); zip.Save(stream2); byte[] bytes = stream2.ToArray(); stream.Close(); stream2.Close(); return bytes; #else throw new System.NotImplementedException ("This method only works with !ASTAR_RECAST_CLASS_BASED_LINKED_LIST"); #endif }
public System.IO.Stream OpenRead() { if (string.IsNullOrWhiteSpace(zipFilePath) && attachments != null) { zipFilePath = System.IO.Path.GetTempFileName(); var saveTo = System.IO.Path.GetTempFileName(); System.IO.File.Delete(zipFilePath); using (var zip = new Ionic.Zip.ZipFile(zipFilePath)) { foreach (var a in attachments) { a.SaveAsFile(saveTo); var fileName = a.FileName; var buf = System.IO.File.ReadAllBytes(saveTo); using (var ms = System.IO.File.Open(saveTo, System.IO.FileMode.Open)) { zip.AddEntry(fileName, ms); zip.Save(); } System.IO.File.Delete(saveTo); } } } return(System.IO.File.Open(zipFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite)); }
public ActionResult PublishedCoursesWSections(int id, string enrollment_term_id) { List <CanvasData.Biz.Model.Course> courses; string token = WebConfigurationManager.AppSettings["CanvasToken"].ToString(); string webURL = WebConfigurationManager.AppSettings["CavasURL"].ToString(); CanvasData.Biz.canvasClient client = new CanvasData.Biz.canvasClient(webURL, token); courses = client.getPublishedCourseswithSections(id.ToString(), enrollment_term_id); List <CanvasData.Biz.Model.Section> sections = new List <CanvasData.Biz.Model.Section>(); foreach (CanvasData.Biz.Model.Course item in courses) { if (item.sections.Count > 0) { sections.AddRange(item.sections); } } var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); serializer.MaxJsonLength = Int32.MaxValue; var mio = new System.IO.MemoryStream(); string coursesCSV = ServiceStack.Text.CsvSerializer.SerializeToCsv(courses); string sectionsCSV = ServiceStack.Text.CsvSerializer.SerializeToCsv(sections); using (var zip = new Ionic.Zip.ZipFile()) { zip.AddEntry("Courses.csv", coursesCSV); zip.AddEntry("Sections.csv", sectionsCSV); zip.Save(mio); } mio.Position = 0; FileStreamResult fs = new FileStreamResult(mio, "text/csv"); fs.FileDownloadName = "PublishedCourses.zip"; return(fs); }
private void ZipFiles() { var files = Directory.GetFiles(textBoxFolder.Text, "*." + textBoxExtension.Text); if (files == null || files.Length == 0) { MessageBox.Show("No files found", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } int index = 1; new Thread(() => { foreach (var file in files) { if (stop) { stop = false; Thread.CurrentThread.Abort(); } var zippedName = textBoxFolder.Text + "\\" + GetFileNameNoExtension(file) + ".zip"; var fileName = GetFileName(file); labelProcessing.Invoke((MethodInvoker) delegate { labelProcessing.Text = fileName; labelProcessing.Refresh(); }); Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(); zip.ParallelDeflateThreshold = -1; zip.AddEntry(fileName, File.ReadAllBytes(file)); if (File.Exists(zippedName)) { File.Delete(zippedName); } zip.Save(zippedName); labelCount.Invoke((MethodInvoker) delegate { labelCount.Text = index.ToString(); labelCount.Refresh(); }); index++; } labelProcessing.Invoke((MethodInvoker) delegate { labelProcessing.Text = "Done!"; labelProcessing.Refresh(); }); }).Start(); }
private void SaveContentXml(Ionic.Zip.ZipFile templateFile, System.Xml.XmlDocument contentXml) { templateFile.RemoveEntry("content.xml"); System.IO.MemoryStream memStream = new System.IO.MemoryStream(); contentXml.Save(memStream); memStream.Seek(0, System.IO.SeekOrigin.Begin); templateFile.AddEntry("content.xml", memStream); }
public static void SaveToAsicSimple(string inputFile, TimeStampToken timeStampToken, string outputFile) { using (Ionic.Zip.ZipFile zipFile = new Ionic.Zip.ZipFile(UTF8Encoding.UTF8)) { zipFile.ParallelDeflateThreshold = -1; zipFile.UseZip64WhenSaving = Ionic.Zip.Zip64Option.Never; zipFile.EmitTimesInUnixFormatWhenSaving = false; zipFile.EmitTimesInWindowsFormatWhenSaving = false; zipFile.Comment = @"mimetype=application/vnd.etsi.asic-s+zip"; using (System.IO.FileStream inputStream = new System.IO.FileStream(inputFile, System.IO.FileMode.Open, System.IO.FileAccess.Read)) using (System.IO.FileStream outputStream = new System.IO.FileStream(outputFile, System.IO.FileMode.Create, System.IO.FileAccess.Write)) { zipFile.AddEntry(@"mimetype", System.Text.UTF8Encoding.UTF8.GetBytes(@"application/vnd.etsi.asic-s+zip")); zipFile.AddEntry(System.IO.Path.GetFileName(inputFile), inputStream); zipFile.AddEntry(@"META-INF/timestamp.tst", timeStampToken.ToByteArray()); zipFile.Save(outputStream); } } }
} // End Sub ZipWithDotNetZip public static void ZipAutoExtract() { using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) { // zip up a directory zip.AddDirectory("C:\\project1\\datafiles", "data"); zip.Comment = "This will be embedded into a self-extracting exe"; zip.AddEntry("Readme.txt", "This is content for a 'Readme' file that will appear in the zip."); zip.SaveSelfExtractor("archive.exe", Ionic.Zip.SelfExtractorFlavor.ConsoleApplication); } // End Using zip } // End Using ZipAutoExtract
public FileResult Zip(Models.Sticker.StickerPackageRequestModel param) { try { if (param == null || !param.Id.HasValue) { throw new OrgException("Invalid sticker package Id"); } StickerBL bl = new StickerBL(); var stickerItems = bl.GetStickerItemByPackageId(param.Id.Value); if (stickerItems.Count == 0) { throw new OrgException("Sticker package not found"); } byte[] zipData = null; using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { using (var zip = new Ionic.Zip.ZipFile()) { foreach (var item in stickerItems) { zip.AddEntry(item.Filename, item.Image); } zip.Save(ms); } zipData = ms.ToArray(); } return(File(zipData, "application/zip", param.Id.Value.ToString() + ".zip")); } catch (OrgException oex) { throw new HttpException((int)System.Net.HttpStatusCode.NotFound, oex.Message); } catch (Exception ex) { if (AppConfigs.DebugInternalMessage) { throw new HttpException((int)System.Net.HttpStatusCode.InternalServerError, ex.Message); } else { throw new HttpException((int)System.Net.HttpStatusCode.NotFound, AppConfigs.InternalErrorMessage); } } }
public void LongNamesJsonSerialization_NormalAndZip_DotNetZip_BlockCopyMethod() { List <GPSPoint1> points = new List <GPSPoint1>(); Random rand = new Random(); for (int i = 0; i < 1000; i++) { points.Add(new GPSPoint1((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), DateTime.Now)); } string output = JsonConvert.SerializeObject(points); byte[] bytes = new byte[output.Length * sizeof(char)]; System.Buffer.BlockCopy(output.ToCharArray(), 0, bytes, 0, bytes.Length); for (int i = 1; i < bytes.Length; i += 2) { Assert.AreEqual(0, bytes[i]); } var length1 = bytes.Length; byte[] compressedData; using (MemoryStream str = new MemoryStream()) { using (var zip = new Ionic.Zip.ZipFile()) { zip.CompressionLevel = CompressionLevel.BestCompression; zip.AddEntry("README.txt", bytes); zip.Save(str); } var r = str.Length; compressedData = str.ToArray(); } //test for unzipping using (MemoryStream dest = new MemoryStream()) { using (MemoryStream str = new MemoryStream(compressedData)) { var entry = Ionic.Zip.ZipFile.Read(str); var firstEntry = entry.First(); firstEntry.Extract(dest); } byte[] endData = dest.ToArray(); for (int i = 0; i < endData.Length; i++) { Assert.AreEqual(bytes[i], endData[i]); } } }
public static void CompressZipByIonic(string sourcePath, string zipPath) { var filelist = GetFileList(sourcePath, new List <String>()); using (var zip = new Ionic.Zip.ZipFile()) { foreach (string file in filelist) { string path = file.Substring(sourcePath.Length + 1); zip.AddEntry(path, File.ReadAllBytes(file)); } zip.Save(zipPath); } }
/// <summary> /// 压缩一个文件返回流信息 /// </summary> /// <param name="filePath">源文件服务器路径</param> /// <param name="fileName">压缩文件名</param> /// <returns></returns> public static byte[] ZipFileOneInfo(string filePath, string fileName) { using (var zipFile = new ZipFile(Encoding.UTF8)) { using (var fileStream = new FileStream(filePath, FileMode.Open)) { zipFile.AddEntry(fileName, fileStream); using (var memoryStream = new MemoryStream()) { zipFile.Save(memoryStream); return(memoryStream.ToArray()); } } } }
public override void ExecuteResult(ControllerContext context) { var response = context.HttpContext.Response; response.ContentType = "application/zip"; response.AppendHeader("content-disposition", "attachment; filename=" + FileName); using (var zipFile = new Ionic.Zip.ZipFile()) { foreach (var e in this.Entries) { zipFile.AddEntry(e.FileName, e.BytesStream); } zipFile.Save(response.OutputStream); } }
/// <summary> /// 向压缩文件中添加Byte[] /// </summary> /// <param name="srcBytes">要添加的数据</param> /// <param name="zipedName">目标文件名</param> /// <param name="encryptKey">加密密码(优先检查), NULL表示不加密</param> /// <param name="licenseKeyType">授权密码类型,0表示不加密</param> public bool AddBytes(byte[] srcBytes, string zipedName, string encryptKey, int licenseKeyType) { if (zipObject == null) { ErrorString = "Create function must called first"; return(false); } if (srcBytes == null || string.IsNullOrWhiteSpace(zipedName)) { ErrorString = "Invalid Parameters"; return(false); } try { //添加到压缩文件中 byte[] encodeBytes = null; if (!string.IsNullOrWhiteSpace(encryptKey) || licenseKeyType > 0) { if (!string.IsNullOrWhiteSpace(encryptKey)) { encodeBytes = Security.EncryptData(srcBytes, encryptKey); } else { encodeBytes = Security.EncryptDataByLicenseKey(srcBytes, licenseKeyType); } if (encodeBytes == null) { ErrorString = Security.ErrorString; return(false); } } else { encodeBytes = srcBytes; } Ionic.Zip.ZipEntry entry = zipObject.AddEntry(zipedName, srcBytes); return(true); } catch (Exception ex) { ErrorString = ex.Message; return(false); } }
/// <summary> /// 压缩一个文件返回流信息 /// </summary> /// <param name="filePath">源文件服务器路径</param> /// <param name="fileName">压缩文件名</param> /// <returns></returns> public static byte[] ZipFileOneInfo(string filePath, string fileName) { using (var zipFile = new ZipFile(Encoding.UTF8)) { using (var fileStream = new FileStream(filePath, FileMode.Open)) { zipFile.AddEntry(fileName, fileStream); using (var memoryStream = new MemoryStream()) { zipFile.Save(memoryStream); return memoryStream.ToArray(); } } } }
public void Save(string path, string fileName, string content, string password) { using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(path)) { zip.Password = password; zip.Encryption = Ionic.Zip.EncryptionAlgorithm.WinZipAes256; if (zip["" + fileName + ""] != null) { zip.RemoveEntry(fileName); } zip.AddEntry(fileName, content, System.Text.Encoding.UTF8); zip.Save(path); } }
void ExportFileZip() { var update = new UpdatePackage("archive") { IncludeAll = true }; var jsout = new JsOutput(update); jsout.Write(); var zip = new Ionic.Zip.ZipFile("export.zip"); zip.UseZip64WhenSaving = Ionic.Zip.Zip64Option.Always; foreach (var row in update.OrderedRows().OfType<DataJsonRow>()) { var path = $"{row.Lang}\\{row.Type}\\{row.Id}.json"; zip.AddEntry(path, row.Json, Encoding.UTF8); } zip.Save(); }
public void LongNamesJsonSerialization_NormalAndZip_DotNetZip_EncodingMethod_PropertyNullable() { List <GPSPoint> points = new List <GPSPoint>(); Random rand = new Random(); for (int i = 0; i < 1000; i++) { points.Add(new GPSPoint((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble())); } var setttings = new JsonSerializerSettings(); setttings.NullValueHandling = NullValueHandling.Ignore; setttings.MissingMemberHandling = MissingMemberHandling.Ignore; string output = JsonConvert.SerializeObject(points, setttings); var bytes = UTF8Encoding.UTF8.GetBytes(output); var length1 = bytes.Length; byte[] compressedData; using (MemoryStream str = new MemoryStream()) { using (var zip = new Ionic.Zip.ZipFile()) { zip.CompressionLevel = CompressionLevel.BestCompression; zip.AddEntry("README.txt", bytes); zip.Save(str); } var r = str.Length; compressedData = str.ToArray(); } //test for unzipping using (MemoryStream dest = new MemoryStream()) { using (MemoryStream str = new MemoryStream(compressedData)) { var entry = Ionic.Zip.ZipFile.Read(str); var firstEntry = entry.First(); firstEntry.Extract(dest); } byte[] endData = dest.ToArray(); for (int i = 0; i < endData.Length; i++) { Assert.AreEqual(bytes[i], endData[i]); } } }
/// <summary> /// Add a entrie in the ZIP archive from <see cref="byte"/>[] /// </summary> /// <param name="entryName"></param> /// <param name="stream"></param> /// <returns></returns> public void AddEntry(string entryName, Stream stream) { try { zipFile.AddEntry(ToEntryFormat(entryName), stream); } catch (Ionic.Zip.ZipException ex) { throw ZipException.FromIonic(ex); } catch (Ionic.Zlib.ZlibException ex) { throw ZipException.FromIonic(ex); } catch (Exception ex) { throw ex; } }
private void OverwriteEpub(string file, string tempFile) { File.Delete(file); using (var zip = new Ionic.Zip.ZipFile()) { var mime = zip.AddEntry("mimetype", "application/epub+zip", Encoding.ASCII); zip.UseZip64WhenSaving = Ionic.Zip.Zip64Option.Never; mime.CompressionLevel = Ionic.Zlib.CompressionLevel.None; mime.CompressionMethod = Ionic.Zip.CompressionMethod.None; var metaDir = Path.Combine(tempFile, "META-INF"); var meta = zip.AddDirectory(metaDir, "META-INF"); meta.CompressionLevel = Ionic.Zlib.CompressionLevel.None; var contentDir = Path.Combine(tempFile, "OEBPS"); var content = zip.AddDirectory(contentDir, "OEBPS"); content.CompressionLevel = Ionic.Zlib.CompressionLevel.None; zip.Save(file); } directory.Delete(tempFile, true); }
/// <summary> /// /// </summary> /// <param name="file"></param> /// <param name="key"></param> /// <param name="compressedName"></param> /// <returns></returns> public virtual File Compress(File file, string key = null, string compressedName = null) { using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) { string fileName = string.IsNullOrEmpty(compressedName) ? file.Name + "zip" : compressedName; using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) { zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression; Ionic.Zip.ZipEntry e = zip.AddEntry(file.Name, file.Content); if (!string.IsNullOrEmpty(key)) { e.Password = key; } zip.Save(ms); } return(new File(fileName, ms.ToArray()) { Compressed = true }); } }
// zzzzzzz // http://blogs.msdn.com/b/dotnetinterop/archive/2008/06/04/dotnetzip-now-can-save-directly-to-asp-net-response-outputstream.aspx public static void ZipToHttpResponse(string DirectoryToZip) { string ReadmeText = "This is a zip file dynamically generated at " + System.DateTime.Now.ToString("G"); System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; Response.Clear(); string fileName = @"Довнлоад.zip"; // @"Довнлоад.зип" fileName = @"Download.zip"; Response.ContentType = "application/zip"; Response.AddHeader("content-disposition", "filename=" + fileName); //using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(Response.OutputStream)) using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(System.Text.Encoding.UTF8)) { // Add to the zip archive, the file selected in the dropdownlist. // zip.AddFile(ListOfFiles.SelectedItem.Text, "files"); // Add a boilerplate copyright file into the zip. // zip.AddFile(@"\static\Copyright.txt", ""); // The string ReadmeText becomes the content for an entry in the zip archive, with the filename "Readme.txt". // zip.AddStringAsFile(ReadmeText, "Readme.txt", ""); zip.Comment = "This will be embedded into a self-extracting exe"; zip.AddEntry("ReadMeZB.txt", ReadmeText); // http://dotnetslackers.com/articles/aspnet/Use-ASP-NET-and-DotNetZip-to-Create-and-Extract-ZIP-Files.aspx // zip.Password = "******"; // zip.Encryption = Ionic.Zip.EncryptionAlgorithm.PkzipWeak; //zip.StatusMessageTextWriter = System.Console.Out; zip.AddDirectory(DirectoryToZip); // recurses subdirectories // zip.Save(); zip.Save(Response.OutputStream); } // End Using zip Response.End(); } // End Sub ZipToHttpResponse
byte[] serializeJson(List <GPSPoint1> points, bool shouldZip) { string output = JsonConvert.SerializeObject(points); var bytes = UTF8Encoding.UTF8.GetBytes(output); var length1 = bytes.Length; byte[] result = bytes; if (shouldZip) { using (MemoryStream str = new MemoryStream()) { using (var zip = new Ionic.Zip.ZipFile()) { zip.CompressionLevel = CompressionLevel.BestCompression; zip.AddEntry("README.txt", bytes); zip.Save(str); } var r = str.Length; result = str.ToArray(); } } return(result); }
public ActionResult export_templates_to_zip(Int32 id = 0, string returnUrl = "") { // Get the current domain Domain currentDomain = Tools.GetCurrentDomain(); ViewBag.CurrentDomain = currentDomain; // Get query parameters ViewBag.QueryParams = new QueryParams(returnUrl); // Check if the administrator is authorized if (Administrator.IsAuthorized(new string[] { "Administrator", "Editor" }) == true) { ViewBag.AdminSession = true; } else if (Administrator.IsAuthorized(Administrator.GetAllAdminRoles()) == true) { ViewBag.AdminSession = true; ViewBag.AdminErrorCode = 1; ViewBag.TranslatedTexts = StaticText.GetAll(currentDomain.back_end_language, "id", "ASC"); return View("index"); } else { // Redirect the user to the start page return RedirectToAction("index", "admin_login"); } // Get all the custom theme templates List<CustomThemeTemplate> templates = CustomThemeTemplate.GetAllPostsByCustomThemeId(id, "user_file_name", "ASC"); // Create the zip file variable Ionic.Zip.ZipFile zipFile = null; // Create a output stream MemoryStream outputStream = new MemoryStream(); // Create the file stream result FileStreamResult fileStreamResult = null; try { // Create a new zip file zipFile = new Ionic.Zip.ZipFile(System.Text.Encoding.UTF8); // Loop all the templates for (int i = 0; i < templates.Count; i++) { // Get the stream byte[] streamData = System.Text.Encoding.UTF8.GetBytes(templates[i].user_file_content); // Add the zip file zipFile.AddEntry(templates[i].user_file_name, streamData); } // Save the zip file zipFile.Save(outputStream); // Go to the beginning of the output stream outputStream.Seek(0, SeekOrigin.Begin); // Create the file stream result fileStreamResult = new FileStreamResult(outputStream, "application/zip") { FileDownloadName = "custom-templates.zip" }; } catch (Exception exception) { string exceptionMessage = ""; exceptionMessage = exception.Message; } finally { // Close streams if (zipFile != null) { zipFile.Dispose(); } } // Return the zip file return fileStreamResult; } // End of the export_templates_to_zip method
public static byte[] GetPackage() { byte[] _zipContent = null; NttDataWA.DocsPaWR.SchedaDocumento _schedaDocumento; DocsPaWR.FileDocumento _filePrincipale; DocsPaWR.FileDocumento _fileTemp; Ionic.Zip.ZipFile _zipFile; System.IO.MemoryStream _tempStream; try { _tempStream = new System.IO.MemoryStream(); _zipFile = new Ionic.Zip.ZipFile(); _schedaDocumento = UIManager.DocumentManager.getSelectedRecord(); var _docPrincipale = _schedaDocumento.documenti[0]; var filePath = _docPrincipale.fileName; if ( filePath.ToUpper().EndsWith(".P7M") || filePath.ToUpper().EndsWith(".TSD") || filePath.ToUpper().EndsWith(".M7M") || filePath.ToUpper().EndsWith(".TSR") ) { _filePrincipale = WsInstance.DocumentoGetFileFirmato(_schedaDocumento.documenti[0], UIManager.UserManager.GetInfoUser()); } else { _filePrincipale = WsInstance.DocumentoGetFile(_schedaDocumento.documenti[0], UIManager.UserManager.GetInfoUser()); } if (_filePrincipale != null && _filePrincipale.content != null && _filePrincipale.content.Length > 0) { _zipFile.AddEntry(_filePrincipale.nomeOriginale, _filePrincipale.content); } int indexAllegato = 0; foreach (var attach in _schedaDocumento.allegati) { filePath = attach.fileName; if ( filePath.ToUpper().EndsWith(".P7M") || filePath.ToUpper().EndsWith(".TSD") || filePath.ToUpper().EndsWith(".M7M") || filePath.ToUpper().EndsWith(".TSR") ) { _fileTemp = WsInstance.DocumentoGetFileFirmato(attach, UIManager.UserManager.GetInfoUser()); } else { _fileTemp = WsInstance.DocumentoGetFile(attach, UIManager.UserManager.GetInfoUser()); } // può essere null ? if (_fileTemp == null || _fileTemp.content == null || _fileTemp.content.Length == 0) { continue; } _zipFile.AddEntry("Allegato_" + ++indexAllegato + "_" + _fileTemp.nomeOriginale, _fileTemp.content); } _zipFile.Save(_tempStream); _zipContent = _tempStream.ToArray(); } catch (Exception ex) { throw ex; } return(_zipContent); }
public override bool Execute() { Log.LogMessage( MessageImportance.Low, "Packing M-Files Application." ); // Gather all the JavaScript files var scripts = new List<string>(); scripts.AddRange( SourceFiles ); // Gather all reference files. // For now we do not support project or zip references so this step doesn't require anything special. var referenceFiles = References ?? new string[] { }; Log.LogMessage( MessageImportance.Low, "Resolving references." ); // Make sure the referenced files exist. var missingFiles = referenceFiles.Where( r => !File.Exists( r ) ).ToList(); foreach( var missingFile in missingFiles ) Log.LogError( "Referenced file '{0}' does not exist.", missingFile ); if( missingFiles.Count > 0 ) return false; // Resolve references by filename. var referencesByName = referenceFiles.GroupBy( f => Path.GetFileName( f ) ); // Resolve the final filenames. var finalReferences = new Dictionary<string, string>(); foreach( var nameGroup in referencesByName ) { var fileName = nameGroup.Key; var files = nameGroup.ToList(); if( fileName.ToLower() == "appdef.xml" ) continue; if( fileName.ToLower() == "_package.js" ) continue; for( int i = 0; i < files.Count; i++ ) { // If there are more than one file with the same name, use a $i as postfix for it. string postfix = ""; if( files.Count > 1 ) postfix = "$" + i; string finalFileName = Path.GetFileNameWithoutExtension( fileName ) + postfix + Path.GetExtension( fileName ); finalReferences[ files[ i ] ] = finalFileName; } } // Generate the package definition. var appdef = new ApplicationDefinition(); appdef.Guid = this.Guid.Replace("{", "").Replace("}", ""); appdef.Name = this.Name; var appfiles = new List<ApplicationFile>(); appfiles.Add( new ApplicationFile { Name = "_package.js" } ); foreach( var environment in new[] { "vaultcore", "vaultui", "shellui" } ) { var module = new ApplicationModule { Environment = environment }; appdef.Modules.Add( module ); module.Files = appfiles; } // Build the zip file. // Add the local scripts. if( File.Exists( OutputFile ) ) File.Delete( OutputFile ); var outputZip = new Ionic.Zip.ZipFile( OutputFile ); foreach( var file in SourceFiles ) { outputZip.AddFile( file ); appfiles.Add( new ApplicationFile { Name = file } ); } // Add the referenced scripts. foreach( var reference in finalReferences ) { var file = reference.Key; if( Path.GetExtension( file ) == ".zip" ) { var inputZip = new Ionic.Zip.ZipFile( file ); foreach( var e in inputZip.Entries ) { var filename = Path.GetFileName( e.FileName ).ToLower(); if( filename == "appdef.xml" ) continue; if( filename == "_package.js" ) continue; var tempStream = new MemoryStream(); e.Extract( tempStream ); tempStream.Position = 0; var projectName = Path.GetFileNameWithoutExtension( reference.Value ); var entryPath = "_references/" + projectName + "/" + e.FileName; outputZip.AddEntry( entryPath, tempStream ); appfiles.Add( new ApplicationFile { Name = entryPath } ); } } else { var entry = outputZip.AddFile( file ); entry.FileName = "_references/" + reference.Value; appfiles.Add( new ApplicationFile { Name = entry.FileName } ); } } var stream = new MemoryStream(); var serializer = new XmlSerializer( typeof( ApplicationDefinition ) ); serializer.Serialize( stream, appdef ); stream.Flush(); stream.Position = 0; outputZip.AddEntry( "appdef.xml", stream ); var packageStream = this.GetType().Assembly.GetManifestResourceStream( "MFiles.SDK.Tasks.Scripts.package.js" ); outputZip.AddEntry( "_package.js", packageStream ); outputZip.Save(); LogArray( "Scripts", outputZip.Entries.Select( e => e.FileName ) ); return true; }
public HttpResponseMessage DownloadFolder(string folderId) { using (var db = new WebDiskDBEntities()) { HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK); string zipName = db.FolderManage.Where(x => x.FolderId == folderId).SingleOrDefault().FolderName; #region Ionic라이브러리로 파일 압축하기 using (var zip = new Ionic.Zip.ZipFile()) { List <string> fileList = GetFileList(folderId, new List <string>()); foreach (var file in fileList) { try { #region 일을 읽어와서 zip entry에 추가 //todo : file 이란 변수가 실제로 파일인것만 stream으로 생성하여 압축 entry 에 추가하기.. //Bytes 배열로 생성 byte[] bytes_file = File.ReadAllBytes(file); #region 해당 폴더 경로만 얻기 int index = file.IndexOf(zipName); //해당 폴더 인덱스 string parsedPath = file.Substring(0, index); //인덱스까지 문자열을 자른다. string result = file.Replace(parsedPath, ""); //파싱한 문자열을 제거한다 //시스템의 기본 인코딩 타입으로 읽어서 byte[] __filename_bytec = System.Text.Encoding.Default.GetBytes(result); // IBM437로 변환해 준다. string IS_FileName = System.Text.Encoding.GetEncoding("IBM437").GetString(__filename_bytec); zip.AddEntry(IS_FileName, bytes_file); #endregion #endregion } catch { return(new HttpResponseMessage() { StatusCode = HttpStatusCode.OK, Content = new StringContent("오류발생 : " + file, System.Text.Encoding.UTF8) }); } } #region 메모리스트림에 zip 파일 저장하기 zip파일로 리턴하기 using (MemoryStream memoryStream = new MemoryStream()) { zip.Save(memoryStream); response.Content = new ByteArrayContent(memoryStream.ToArray()); response.Content.Headers.ContentLength = memoryStream.ToArray().LongLength; response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); response.Content.Headers.ContentDisposition.FileName = $"{zipName}_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.zip"; response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip"); } #endregion } #endregion return(response); } }
/// <summary> /// 解析指定压缩存档 /// </summary> /// <param name="path">压缩存档路径</param> /// <returns></returns> public static SaveData Parse(string path) { SaveData ans = null; if (!path.EndsWith(".zip")) { if (File.Exists(Path.Combine(path, "date.json"))) { var content = File.ReadAllText(Path.Combine(path, "date.json")); ans = JsonConvert.DeserializeObject(content, typeof(SaveData)) as SaveData; } else if (!File.Exists(Path.Combine(path, "TW_Save_Date_0.twV0")) && !File.Exists(Path.Combine(path, "TW_Save_Date_0.tw"))) { throw new System.Exception(path); } else { string file = null; bool rijndeal = true; if (File.Exists(Path.Combine(path, "TW_Save_Date_0.twV0"))) { file = Path.Combine(path, "TW_Save_Date_0.twV0"); rijndeal = false; } else { file = Path.Combine(path, "TW_Save_Date_0.tw"); rijndeal = true; } DateFile.SaveDate date = null; try { date = typeof(SaveDateFile) .GetMethod("GetData", BindingFlags.Public | BindingFlags.Instance) .Invoke(SaveDateFile.instance, new object[] { file, typeof(DateFile.SaveDate), rijndeal }) as DateFile.SaveDate; } catch (AmbiguousMatchException) { date = typeof(SaveDateFile) .GetMethod("GetData", BindingFlags.Public | BindingFlags.Instance) .Invoke(SaveDateFile.instance, new object[] { file, typeof(DateFile.SaveDate) }) as DateFile.SaveDate; } ans = new SaveData(date._mainActorName, date._year, date._samsara, date._dayTrun, date._playerSeatName, date._playTime); File.WriteAllText(Path.Combine(path, "date.json"), JsonConvert.SerializeObject(ans)); } } else { using (var zip = new Ionic.Zip.ZipFile(path)) { if (zip.ContainsEntry("date.json")) { using (var stream = new MemoryStream()) { zip.SelectEntries("date.json").First().Extract(stream); stream.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(stream)) { var serializer = JsonSerializer.Create(); ans = serializer.Deserialize(reader, typeof(SaveData)) as SaveData; } } } else if (!zip.ContainsEntry("TW_Save_Date_0.twV0") && !zip.ContainsEntry("TW_Save_Date_0.tw")) { throw new System.Exception(path); // 错误存档 } else // 不含加速文件 { var tmp = Path.Combine( System.Environment.GetEnvironmentVariable("TEMP"), "SaveDate.tw"); if (File.Exists(tmp)) { File.Delete(tmp); } bool rijndeal = true; using (var stream = File.OpenWrite(tmp)) { if (zip.ContainsEntry("TW_Save_Date_0.twV0")) { zip.SelectEntries("TW_Save_Date_0.twV0").First().Extract(stream); rijndeal = false; } else if (zip.ContainsEntry("TW_Save_Date_0.tw")) { zip.SelectEntries("TW_Save_Date_0.tw").First().Extract(stream); rijndeal = true; } } DateFile.SaveDate date = null; try { date = typeof(SaveDateFile) .GetMethod("GetData", BindingFlags.Public | BindingFlags.Instance) .Invoke(SaveDateFile.instance, new object[] { tmp, typeof(DateFile.SaveDate), rijndeal }) as DateFile.SaveDate; } catch (AmbiguousMatchException) { date = typeof(SaveDateFile) .GetMethod("GetData", BindingFlags.Public | BindingFlags.Instance) .Invoke(SaveDateFile.instance, new object[] { tmp, typeof(DateFile.SaveDate) }) as DateFile.SaveDate; } ans = new SaveData(date._mainActorName, date._year, date._samsara, date._dayTrun, date._playerSeatName, date._playTime); // 添加加速文件 zip.AddEntry("date.json", JsonConvert.SerializeObject(ans)); zip.Save(); } } } return(ans); }