public static bool ZipBytes(byte[] _bytes, string _outputPathName, string _password = null, ZipCallback _zipCallback = null) { if ((null == _bytes) || string.IsNullOrEmpty(_outputPathName)) { Debug.Log(_bytes + " 文件流为空"); return(false); } if (!Directory.Exists(_outputPathName)) { Directory.CreateDirectory(_outputPathName); } Debug.Log(_outputPathName); _outputPathName = PathRespace(_outputPathName); string _fileName = Path.Combine(_outputPathName, "ttjkz.zip"); _fileName = PathRespace(_fileName); Debug.LogError(_fileName); ZipOutputStream zipOutputStream = new ZipOutputStream(File.Create(_fileName)); zipOutputStream.SetLevel(6); // 压缩质量和压缩速度的平衡点 ZipEntry entry = null; FileStream fileStream = null; try { string entryName = Path.Combine("/", Path.GetFileName(_fileName)); entryName = PathRespace(entryName); Debug.Log("entryName:" + entryName); entry = new ZipEntry(entryName); entry.DateTime = System.DateTime.Now; if ((null != _zipCallback) && !_zipCallback.OnPreZip(entry)) { return(true); // 过滤 } entry.Size = _bytes.Length; //crc32.Reset(); //crc32.Update(buffer); //entry.Crc = crc32.Value; zipOutputStream.PutNextEntry(entry); zipOutputStream.Write(_bytes, 0, _bytes.Length); } catch (System.Exception _e) { Debug.LogError("[ZipUtility.ZipFile]: " + _e.ToString()); return(false); } finally { if (null != fileStream) { fileStream.Flush(); fileStream.Close(); fileStream.Dispose(); } } if (null != _zipCallback) { _zipCallback.OnPostZip(entry); } //return true; zipOutputStream.Flush(); zipOutputStream.Finish(); zipOutputStream.Close(); zipOutputStream.Dispose(); return(true); }
/// <summary> /// Writes zip file to memory stream. /// </summary> /// <param name="filesToZip">The files to zip.</param> /// <param name="path">The destination path.</param> /// <param name="compression">The compression level.</param> public static MemoryStream ToMemoryStream(string sourceFile) { //memory stream MemoryStream msCompressed = new MemoryStream(); //reading buffer byte[] mBuffer = new Byte[200000]; //bytes read out int bytesRead; //create new zip archive ZipOutputStream zipStream = new ZipOutputStream(msCompressed); zipStream.SetLevel(9); //create new checksum Crc32 crc32 = new Crc32(); //create new zip entry FileInfo fi = new FileInfo(sourceFile); ZipEntry entry = new ZipEntry(Path.GetFileName(sourceFile)); entry.DateTime = fi.LastWriteTime; entry.Size = fi.Length; //open source file FileStream sourceFileStream = File.OpenRead(sourceFile); //reset CRC crc32.Reset(); //add new entry to zip file zipStream.PutNextEntry(entry); //read source file while (sourceFileStream.Position < sourceFileStream.Length) { bytesRead = sourceFileStream.Read(mBuffer, 0, mBuffer.Length); zipStream.Write(mBuffer, 0, bytesRead); crc32.Update(mBuffer, 0, bytesRead); } //store CRC value of this entry entry.Crc = crc32.Value; //close entry zipStream.CloseEntry(); //close source file sourceFileStream.Close(); //close zip archive zipStream.Finish(); zipStream.Flush(); //don't close stream here //zipStream.Close(); //zipStream.Dispose(); msCompressed.Position = 0; return(msCompressed); }
/// <summary> /// 递归压缩文件夹 /// </summary> /// <param name="folderToZip">要压缩的文件夹路径</param> /// <param name="zipStream">压缩输出流</param> /// <param name="parentFolderName">此文件夹的上级文件夹</param> /// <returns></returns> private static bool ZipDirectoryByIteration(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) + "/")); /* 外层不带有文件夹 */ if (!string.IsNullOrEmpty(parentFolderName)) { ent = new ZipEntry(parentFolderName); zipStream.PutNextEntry(ent); zipStream.Flush(); } files = Directory.GetFiles(folderToZip); foreach (string file in files) { fs = System.IO.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 = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(file))); ent.DateTime = DateTime.Now; ent.Size = fs.Length; fs.Close(); crc.Reset(); /* 计算文件流的crc码 */ crc.Update(buffer); /* 把crc码放到压缩类的crc属性里,类库会自行检验。 */ ent.Crc = crc.Value; zipStream.PutNextEntry(ent); zipStream.Write(buffer, 0, buffer.Length); } } catch (Exception e) { 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 (!ZipDirectoryByIteration(folder, zipStream, Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/"))) if (!ZipDirectoryByIteration(folder, zipStream, Path.Combine(parentFolderName, Path.GetFileName(folder) + "/"))) { return(false); } } return(result); }
private void ExportAllData() { using (var stream = TempStream.Create()) { var contactDao = _daoFactory.GetContactDao(); var contactInfoDao = _daoFactory.GetContactInfoDao(); var dealDao = _daoFactory.GetDealDao(); var casesDao = _daoFactory.GetCasesDao(); var taskDao = _daoFactory.GetTaskDao(); var historyDao = _daoFactory.GetRelationshipEventDao(); _totalCount += contactDao.GetAllContactsCount(); _totalCount += dealDao.GetDealsCount(); _totalCount += casesDao.GetCasesCount(); _totalCount += taskDao.GetAllTasksCount(); _totalCount += historyDao.GetAllItemsCount(); using (var zipStream = new ZipOutputStream(stream, true)) { zipStream.PutNextEntry("contacts.csv"); var contactData = contactDao.GetAllContacts(); var contactInfos = new StringDictionary(); contactInfoDao.GetAll() .ForEach(item => { var contactInfoKey = String.Format("{0}_{1}_{2}", item.ContactID, (int)item.InfoType, item.Category); if (contactInfos.ContainsKey(contactInfoKey)) { contactInfos[contactInfoKey] += "," + item.Data; } else { contactInfos.Add(contactInfoKey, item.Data); } }); var zipEntryData = new MemoryStream(Encoding.UTF8.GetBytes(ExportContactsToCSV(contactData, contactInfos))); zipEntryData.StreamCopyTo(zipStream); zipStream.PutNextEntry("oppotunities.csv"); var dealData = dealDao.GetAllDeals(); zipEntryData = new MemoryStream(Encoding.UTF8.GetBytes(ExportDealsToCSV(dealData))); zipEntryData.StreamCopyTo(zipStream); zipStream.PutNextEntry("cases.csv"); var casesData = casesDao.GetAllCases(); zipEntryData = new MemoryStream(Encoding.UTF8.GetBytes(ExportCasesToCSV(casesData))); zipEntryData.StreamCopyTo(zipStream); zipStream.PutNextEntry("tasks.csv"); var taskData = taskDao.GetAllTasks(); zipEntryData = new MemoryStream(Encoding.UTF8.GetBytes(ExportTasksToCSV(taskData))); zipEntryData.StreamCopyTo(zipStream); zipStream.PutNextEntry("history.csv"); var historyData = historyDao.GetAllItems(); zipEntryData = new MemoryStream(Encoding.UTF8.GetBytes(ExportHistoryToCSV(historyData))); zipEntryData.StreamCopyTo(zipStream); zipStream.Flush(); zipStream.Close(); stream.Position = 0; } var assignedURI = _dataStore.SavePrivate(String.Empty, "exportdata.zip", stream, DateTime.Now.AddDays(1)); Status = assignedURI; _notifyClient.SendAboutExportCompleted(_author.ID, assignedURI); Complete(); } }
private static void HandleFolder(string compressFolder, string zipFileName, bool removeZippedFolder) { int compressionLevel = 9; if (!compressFolder.EndsWith(Path.DirectorySeparatorChar.ToString())) { compressFolder += Path.DirectorySeparatorChar.ToString(); } List <Tuple <bool, string> > removeList = new List <Tuple <bool, string> >(); List <string> dirs = new List <string>(Directory.EnumerateDirectories(compressFolder, "*.*", SearchOption.AllDirectories)); dirs.Sort((x, y) => y.CompareTo(x)); using (ZipOutputStream zipOutput = new ZipOutputStream(File.Create(zipFileName))) { zipOutput.SetLevel(compressionLevel); foreach (string dir in dirs) { WriteEntry(zipOutput, compressFolder, false, dir); } dirs.Add(compressFolder); foreach (string dir in dirs) { IEnumerable <string> fileNames = Directory.EnumerateFiles(dir, "*.*", SearchOption.TopDirectoryOnly); foreach (string filename in fileNames) { if (string.Compare(filename, zipFileName) == 0) { continue; } WriteEntry(zipOutput, compressFolder, true, filename); if (removeZippedFolder) { removeList.Add(new Tuple <bool, string>(true, filename)); } } if (removeZippedFolder) { removeList.Add(new Tuple <bool, string>(false, dir)); } } zipOutput.Flush(); } foreach (Tuple <bool, string> entry in removeList) { if (entry.Item1) { File.Delete(entry.Item2); } else { if (Directory.GetFileSystemEntries(entry.Item2).Length == 0) { Directory.Delete(entry.Item2); } } } }
/// <summary> /// 遍历压缩文件夹文件 /// </summary> /// <param name="directoryPath"></param> /// <param name="zipStream"></param> /// <param name="parentDirectoryPath"></param> /// <returns></returns> private static bool CompressDirectory(string directoryPath, ZipOutputStream zipStream, string parentDirectoryPath = "", bool isRoot = false) { ZipEntry zipEntry = null; FileStream fileStream = null; string entryDirectoryPath = ""; bool result = false; try { if (!isRoot) { entryDirectoryPath = Path.Combine(parentDirectoryPath, Path.GetFileName(directoryPath) + "\\"); zipEntry = new ZipEntry(entryDirectoryPath); zipStream.PutNextEntry(zipEntry); zipStream.Flush(); } else { entryDirectoryPath = Path.Combine(parentDirectoryPath); } string[] filePathList = Directory.GetFiles(directoryPath); foreach (string filePath in filePathList) { fileStream = File.OpenRead(filePath); byte[] buffer = new byte[fileStream.Length]; fileStream.Read(buffer, 0, buffer.Length); zipEntry = new ZipEntry(Path.Combine(entryDirectoryPath + Path.GetFileName(filePath))); zipEntry.DateTime = DateTime.Now; zipEntry.Size = fileStream.Length; fileStream.Close(); zipStream.PutNextEntry(zipEntry); zipStream.Write(buffer, 0, buffer.Length); } result = true; } catch { throw; } finally { if (zipEntry != null) { zipEntry = null; } if (fileStream != null) { fileStream.Close(); } } string[] childDirectoryPathList = Directory.GetDirectories(directoryPath); foreach (string childDirectoryPath in childDirectoryPathList) { if (!CompressDirectory(childDirectoryPath, zipStream, entryDirectoryPath, isRoot)) { return(false); } } return(result); }
/// <summary> /// 递归压缩文件夹方法 /// </summary> /// <param name="FolderToZip"></param> /// <param name="ZOPStream">压缩文件输出流对象</param> /// <param name="ParentFolderName"></param> private bool ZipFileDictory(string FolderToZip, ZipOutputStream ZOPStream, 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) + "/")); //加上 “/” 才会当成是文件夹创建 ZOPStream.PutNextEntry(entry); ZOPStream.Flush(); //先压缩文件,再递归压缩文件夹 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); entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/" + Path.GetFileName(file))); entry.DateTime = DateTime.Now; entry.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; ZOPStream.PutNextEntry(entry); ZOPStream.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); } folders = Directory.GetDirectories(FolderToZip); foreach (string folder in folders) { if (!ZipFileDictory(folder, ZOPStream, Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip)))) { return(false); } } return(res); }
/// <summary> /// 递归压缩文件夹方法,实际的处理方法 /// </summary> /// <param name="cfg">压缩配置</param> /// <param name="FolderToZip">待压缩目录</param> /// <param name="s">zip压缩文件流</param> /// <param name="ParentFolderName">待压缩目录所处的父目录</param> private static bool ZipFileDictory(ZipConfig cfg, string FolderToZip, ZipOutputStream s, string ParentFolderName) { //勾选全部备份,则包含temp目录 //if (!ContainTemp && FolderToZip.Substring(FolderToZip.Length - 5, 5).ToLower().Equals(@"\temp")) return true; string dirPath = FolderToZip.ToLower().TrimEnd('\\') + "\\"; if (cfg.IgnoreDirs.FirstOrDefault(p => function.VToP(p).ToLower().Equals(dirPath)) != null) { return(true); } 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) + "/")); //加上 “/” 才会当成是文件夹创建 //entry.CompressionMethod = CompressionMethod.Stored;//如果有报错match则加上此句 s.PutNextEntry(entry); s.Flush(); //先压缩文件,再递归压缩文件夹 filenames = Directory.GetFiles(FolderToZip); foreach (string file in filenames) { //如已在忽略列表,或是正在压缩的文件,则忽略 if (cfg.IgnoreFiles.FirstOrDefault(p => function.VToP(p).ToLower().Equals(file.ToLower())) != null || cfg.ZipSavePath.ToLower().Equals(file.ToLower())) { cfg.Result.P_Position++; continue; } //打开压缩文件 fs = File.OpenRead(file); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/" + Path.GetFileName(file))); 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); cfg.Result.P_Position++; } } catch { 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(cfg, folder, s, Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip)))) { return(false); } } return(res); }
/// <summary> /// This method generate the package as per the <c>PackageSize</c> declare. /// Currently <c>PackageSize</c> is 2 GB. /// </summary> /// <param name="inputFolderPath">Input folder Path.</param> /// <param name="outputFolderandFile">Output folder Path.</param> static void SplitZipFolder(string inputFolderPath, string outputFolderandFile, string threadId) { #region otherApproach #endregion int cnt = 1; m_packageSize = m_packageSize * 20; ArrayList htmlFile = new ArrayList(); ArrayList ar = GenerateFileList(inputFolderPath, out htmlFile); // generate file list // Output Zip file name. string outPath = Path.Combine(outputFolderandFile, threadId + "-" + cnt + ".zip"); long HTMLstreamlenght = 0; using (ZipOutputStream oZipStream = CreateNewStream(htmlFile, outPath, out HTMLstreamlenght)) { // Initialize the zip entry object. ZipEntry oZipEntry = new ZipEntry(); // numbers of files in file list. var counter = ar.Count; try { using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) { Array.Sort(ar.ToArray()); // Sort the file list array. foreach (string Fil in ar.ToArray()) // for each file, generate a zip entry { if (!Fil.EndsWith(@"/")) // if a file ends with '/' its a directory { if (!zip.ContainsEntry(Path.GetFileName(Fil.ToString()))) { oZipEntry = zip.AddEntry("Attachments/" + Path.GetFileName(Fil.ToString()), Fil); counter--; try { if (counter >= 0) { long streamlenght = HTMLstreamlenght; const int BufferSize = 4096; byte[] obuffer = new byte[BufferSize]; if (oZipStream.Position + streamlenght < m_packageSize) { using (FileStream ostream = File.OpenRead(Fil)) { //ostream = File.OpenRead(Fil); using (ZipOutputStream tempZStream = new ZipOutputStream(File.Create(Directory.GetCurrentDirectory() + "\\test.zip"), false)) { tempZStream.PutNextEntry(oZipEntry.FileName); int tempread; while ((tempread = ostream.Read(obuffer, 0, obuffer.Length)) > 0) { tempZStream.Write(obuffer, 0, tempread); } streamlenght = tempZStream.Position; tempZStream.Dispose(); tempZStream.Flush(); tempZStream.Close(); // close the zip stream. // ostream.Dispose(); } File.Delete(Directory.GetCurrentDirectory() + "\\test.zip"); } } if (oZipStream.Position + streamlenght > m_packageSize) { zip.RemoveEntry(oZipEntry); zip.Dispose(); oZipStream.Dispose(); oZipStream.Flush(); oZipStream.Close(); // close the zip stream. cnt = cnt + 1; outPath = Path.Combine(outputFolderandFile, threadId + "-" + cnt.ToString() + ".zip"); // create new output zip file when package size. using (ZipOutputStream oZipStream2 = CreateNewStream(htmlFile, outPath, out HTMLstreamlenght)) { oZipStream2.PutNextEntry(oZipEntry.FileName); using (FileStream ostream = File.OpenRead(Fil)) { int read; while ((read = ostream.Read(obuffer, 0, obuffer.Length)) > 0) { oZipStream2.Write(obuffer, 0, read); } } } } else { oZipStream.PutNextEntry(oZipEntry.FileName); using (FileStream ostream = File.OpenRead(Fil)) { int read; while ((read = ostream.Read(obuffer, 0, obuffer.Length)) > 0) { oZipStream.Write(obuffer, 0, read); } } } } else { Console.WriteLine("No more file existed in directory"); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); zip.RemoveEntry(oZipEntry.FileName); } } else { Console.WriteLine("File Existed {0} in Zip {1}", Path.GetFullPath(Fil.ToString()), outPath); } } } zip.Dispose(); } oZipStream.Dispose(); oZipStream.Flush(); oZipStream.Close();// close stream } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { oZipStream.Dispose(); oZipStream.Flush(); oZipStream.Close();// close stream Console.WriteLine("Remain Files{0}", counter); } } }
/// <summary> /// 压缩文件 /// </summary> /// <param name="filePath">压缩文件路径</param> /// <param name="sourcePath">待压缩文件路径/待压缩目录</param> /// <returns></returns> public static async Task Compress(string filePath, params string[] sourcePath) { //格式化后缀 filePath = Path.ChangeExtension(filePath, ".zip"); //创建保存目录 CreateDirectories(Path.GetDirectoryName(filePath)); //压缩文件根目录 string rootDirectory; using (ZipOutputStream zipStream = new ZipOutputStream(File.Create(filePath))) { zipStream.SetLevel(9); // 压缩级别 0-9 //0为最大 9为最小 foreach (var sourceItem in sourcePath) { rootDirectory = Path.GetDirectoryName(sourceItem) + Path.DirectorySeparatorChar; await WriteCompress(sourceItem, zipStream); } zipStream.Flush(); } async Task WriteCompress(string path, ZipOutputStream zipStream) { if (File.Exists(path)) { //压缩 using (FileStream fileStream = File.OpenRead(path)) { byte[] buffer = new byte[fileStream.Length]; await fileStream.ReadAsync(buffer, 0, buffer.Length); Crc32 crc = new Crc32(); crc.Reset(); crc.Update(buffer); //获得文件位于压缩路径中的相对路径 string tempFile = path.Replace(rootDirectory, ""); //相对路径与原路径相同时,代表这是一个单独的文件 //一般是不会压缩不同路径下的文件,这里特殊处理一下 if (string.Equals(tempFile, path)) { tempFile = Path.GetFileName(tempFile); } ZipEntry entry = new ZipEntry(tempFile); entry.DateTime = DateTime.Now; entry.Size = fileStream.Length; entry.Crc = crc.Value; zipStream.PutNextEntry(entry); await zipStream.WriteAsync(buffer, 0, buffer.Length); } } else if (Directory.Exists(path)) { var all = Directory.GetFileSystemEntries(path); foreach (var item in all) { await WriteCompress(item, zipStream); } } } }
/// <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); } var dictionaryList = PrepareFileSystementities(sourceList); using (ZipOutputStream zipStream = new ZipOutputStream(File.Create(zipFilePath))) { zipStream.Password = password; //设置密码 zipStream.SetComment(comment); //添加注释 zipStream.SetLevel(compressionLevel); //设置压缩等级 foreach (var file in dictionaryList) //从字典取文件添加到压缩文件 { if (!file.IsDirectory) //判断是文件还是文件夹 { FileInfo fileItem = new FileInfo(file.Path); using (FileStream readStream = fileItem.Open(FileMode.Open, FileAccess.Read, FileShare.Read)) { ZipEntry zipEntry = new ZipEntry(file.Name); zipEntry.DateTime = fileItem.LastWriteTime; zipEntry.Size = readStream.Length; zipStream.PutNextEntry(zipEntry); int readLength = 0; byte[] buffer = new byte[2048]; do { readLength = readStream.Read(buffer, 0, 2048); zipStream.Write(buffer, 0, readLength); } while (readLength == 2048); readStream.Close(); } } else//对文件夹的处理 { ZipEntry zipEntry = new ZipEntry(file.Name + "/"); zipStream.PutNextEntry(zipEntry); } } zipStream.Flush(); zipStream.Finish(); zipStream.Close(); } result = true; } catch (Exception ex) { throw new Exception("压缩文件失败", ex); } return(result); }
public ActionResult DownloadCompressFiles(string projectGuid, string fileGuidsText, string folderGuidsText, bool isSearchFile = false) { var dms = GetDMSAndCheckPermission(projectGuid, PermissionType.Read); var fileGuids = string.IsNullOrWhiteSpace(fileGuidsText) ? new List <string>() : CommUtils.Split(fileGuidsText).ToList(); var folderGuids = string.IsNullOrWhiteSpace(folderGuidsText) ? new List <string>() : CommUtils.Split(folderGuidsText).ToList(); CommUtils.Assert(fileGuids.Count != 0 || folderGuids.Count != 0, "必须选择一个[文件/文件夹]进行下载"); //获取待压缩文件夹下的所有文件/文件夹路径 var dictAllFiles = new Dictionary <string, string>(); var allEmptyFolderPath = new List <string>(); if (folderGuids.Count != 0) { var folderAndFilePath = new Tuple <List <string>, Dictionary <string, string> >(new List <string>(), new Dictionary <string, string>()); folderAndFilePath = GetCompressFilesPath(dms, folderGuids, null, folderAndFilePath); dictAllFiles = folderAndFilePath.Item2; allEmptyFolderPath = folderAndFilePath.Item1; } //获取所有待压缩文件的路径 var files = new List <DMSFile>(); foreach (var fileGuid in fileGuids) { CommUtils.Assert(m_dbAdapter.DMSFile.isExistDMSFile(fileGuid), "找不到文件fileGuid[{0}],请刷新页面后重试", fileGuid); var dmsFile = m_dbAdapter.DMSFile.GetByGuid(fileGuid); var projectId = m_dbAdapter.DMSTask.GetProjectIdByDMSId(dms.Instance.Id); CommUtils.AssertEquals(dmsFile.DMSId, dms.Instance.Id, "找不到文件[fileGuid={0}][DMSGuid={1}]", fileGuid, dms.Instance.Guid); dictAllFiles[fileGuid] = dmsFile.Name; files.Add(dmsFile); } //处理重名文件 var keys = dictAllFiles.Keys.ToList(); var dictResultAllFiles = new Dictionary <string, string>(); var allFilesPath = new List <string>(); foreach (var key in keys) { dictResultAllFiles[key] = GetNewPathForDupes(dictAllFiles[key], allFilesPath); allFilesPath.Add(dictResultAllFiles[key]); } //压缩-结束 var resultFilePath = new List <string>(); var dictResultFilePath = new Dictionary <string, string>(); foreach (var fileGuid in dictResultAllFiles.Keys) { var dmsFile = m_dbAdapter.DMSFile.GetByGuid(fileGuid); var repoFile = Platform.Repository.GetFile(dmsFile.RepoFileId); var filePath = repoFile.GetFilePath(); resultFilePath.Add(filePath); dictResultFilePath[filePath] = dictResultAllFiles[fileGuid]; } var ms = new MemoryStream(); ZipOutputStream zipStream = new ZipOutputStream(ms); zipStream.SetLevel(3); CompressFiles(zipStream, WebConfigUtils.RepositoryFilePath, resultFilePath, dictResultFilePath, allEmptyFolderPath); zipStream.Flush(); zipStream.Finish(); ms.Seek(0, SeekOrigin.Begin); //设置压缩包名称 var resultZipFileName = string.Empty; if (isSearchFile) { resultZipFileName = "工作文件"; } else { if (fileGuids.Count == 0 && folderGuids.Count == 1) { var currentFolder = dms.FindFolder(folderGuids.First()); var currFolder = currentFolder.Instance; resultZipFileName = currFolder.Name; var fileSeriesList = currentFolder.Files.GroupToDictList(x => x.FileSeries); fileSeriesList.ToList().ForEach(x => { m_dbAdapter.DMSProjectLog.AddDmsProjectLog(projectGuid, x.Key.Guid, "下载[" + x.Key.Name + "]合并于[" + resultZipFileName + ".zip]"); }); } if (fileGuids.Count != 0 && folderGuids.Count == 0) { var fileSeries = files.ConvertAll(x => x.DMSFileSeriesId).ToList(); var currFileSeries = m_dbAdapter.DMSFileSeries.GetById(files.First().DMSFileSeriesId); if (fileSeries.Distinct().ToList().Count == 1) { resultZipFileName = currFileSeries.Name; } else { var currFolder = m_dbAdapter.DMSFolder.GetById(currFileSeries.DMSFolderId); resultZipFileName = currFolder.ParentFolderId.HasValue ? currFolder.Name : "工作文件"; } } if (string.IsNullOrEmpty(resultZipFileName)) { var currFolder = dms.FindFolder(folderGuids.First()).Instance; var parentFolder = m_dbAdapter.DMSFolder.GetById(currFolder.ParentFolderId.Value); resultZipFileName = parentFolder.ParentFolderId.HasValue ? parentFolder.Name : "工作文件"; } } // m_dbAdapter.DMSProjectLog.AddDmsProjectLog(projectGuid, "下载[" + resultZipFileName + ".zip]"); return(File(ms, "application/octet-stream", resultZipFileName + ".zip")); }
/// <summary> /// 递归压缩文件夹方法 /// </summary> private static bool ZipFileDictory(string folderToZip, ZipOutputStream s, string parentFolderName, List <DirectoryInfo> eliminateInfos, List <FileInfo> eliminateFileInfos) { bool res = true; string[] folders, filenames; ZipEntry entry = null; FileStream fs = null; ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.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) { FileInfo fileInfo = new FileInfo(file); if (eliminateFileInfos.Contains(fileInfo)) { continue; } fs = File.OpenRead(file); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); string folderZipName = Path.GetFileName(folderToZip); folderZipName = string.IsNullOrEmpty(folderZipName) ? string.Empty : string.Concat(folderZipName, "/"); entry = new ZipEntry(Path.Combine(parentFolderName, folderZipName + Path.GetFileName(file))); 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); } folders = Directory.GetDirectories(folderToZip); foreach (string folder in folders) { DirectoryInfo folderInfo = new DirectoryInfo(folder); if (eliminateInfos.Contains(folderInfo)) { continue; } if (!ZipFileDictory(folder, s , Path.Combine(parentFolderName, Path.GetFileName(folderToZip)), eliminateInfos, eliminateFileInfos)) { return(false); } } return(res); }
private static void GenerateUpdatePackages(BuildAssetConfig assetConfig) { ResourceConfig oldConfig = LoadFileFromPackage(assetConfig.packagePath, VERFILE_CONF_PATH); ResourceConfig oldUpdateConfig = null; if (string.IsNullOrEmpty(assetConfig.updatePackagePath)) { oldUpdateConfig = new ResourceConfig(); } else { oldUpdateConfig = LoadFileFromPackage(assetConfig.updatePackagePath, UPDATELIST_CONF_PATH); } // old files md5 Dictionary <string, string> oldFileMd5 = new Dictionary <string, string>(); foreach (var item in oldConfig.resource.patchLst) { oldFileMd5[item.file] = item.md5; } foreach (var item in oldUpdateConfig.resource.patchLst) { oldFileMd5[item.file] = item.md5; } // load new verfile and caculate new verfile md5 AssetBundle newVerfileBundle = null; ResourceConfig verfileConfig = new ResourceConfig(); string verfileHashValue = string.Empty; try { byte[] verfileBytes = File.ReadAllBytes(Path.Combine(BuildOutputPath, VERFILE_CONF_PATH)); newVerfileBundle = AssetBundle.LoadFromMemory(verfileBytes); string verfileText = newVerfileBundle.LoadAsset <TextAsset>(newVerfileBundle.GetAllAssetNames()[0]).text; verfileConfig.Initialize(verfileText); ResourceConfig tempVersionJson = new ResourceConfig(); tempVersionJson.Initialize(verfileText); tempVersionJson.resource.patchLst.RemoveAll((item) => { return(item.file.Contains("verfile") || item.file.Contains("updatelist")); }); verfileHashValue = Utils.HashToMd5(Pathfinding.Serialization.JsonFx.JsonWriter.Serialize(tempVersionJson.resource)); } finally { if (null != newVerfileBundle) { newVerfileBundle.Unload(false); newVerfileBundle = null; } } ResourceConfig updateConfig = new ResourceConfig(); updateConfig.resource.hashValue = verfileHashValue; ConfResourceItem verfileItem = null; foreach (var newItem in verfileConfig.resource.patchLst) { if (newItem.file.Contains("updatelist")) { continue; } if (newItem.file.Contains("verfile")) { newItem.md5 = Utils.FileToMd5(Path.Combine(BuildOutputPath, VERFILE_CONF_PATH)); verfileItem = newItem; continue; } var oldItemMd5 = string.Empty; oldFileMd5.TryGetValue(newItem.file, out oldItemMd5); // add or modify if (string.IsNullOrEmpty(oldItemMd5) || oldItemMd5 != newItem.md5) { updateConfig.resource.patchLst.Add(newItem); } } if (updateConfig.resource.patchLst.Count <= 0) { updateConfig.resource.hashValue = oldUpdateConfig.resource.hashValue; } else { updateConfig.resource.patchLst.Add(verfileItem); } // set need copy asset map Dictionary <string, string> needCopyMap = new Dictionary <string, string>(); foreach (var item in updateConfig.resource.patchLst) { needCopyMap.Add(item.file, Path.Combine(BuildOutputPath, item.file)); } needCopyMap[UPDATELIST_CONF_PATH] = Path.Combine(BuildOutputPath, UPDATELIST_CONF_PATH); // add old update list to new, but don't need to copy foreach (var item in oldUpdateConfig.resource.patchLst) { // this is the old update list if (item.file.Contains("updatelist")) { continue; } if (updateConfig.resource.patchLst.FindAll(fileItem => { return(fileItem.file == item.file); }).Count <= 0) { updateConfig.resource.patchLst.Add(item); } } string updateListConfigText = SerializeJsonFile(updateConfig.resource, UPDATELIST_JSON_PATH); string tempDirectory = Path.Combine(Application.dataPath, "../" + FileUtil.GetUniqueTempPathInProject()); if (!Directory.Exists(tempDirectory)) { Directory.CreateDirectory(tempDirectory); } AssetBundleBuild[] buildMap = new AssetBundleBuild[] { new AssetBundleBuild() { assetBundleName = UPDATELIST_CONF_PATH, assetNames = new string[] { "Assets/data/conf/updatelist.json" } }, }; BuildPipeline.BuildAssetBundles(tempDirectory, buildMap, BuildAssetBundleOptions.ChunkBasedCompression, CurrentBuildTarget); CopyFileEx(Path.Combine(tempDirectory, UPDATELIST_CONF_PATH), Path.Combine(BuildOutputPath, UPDATELIST_CONF_PATH)); using (MemoryStream compressed = new MemoryStream()) { using (ZipOutputStream compressor = new ZipOutputStream(compressed)) { int count = 0; try { compressor.SetComment(updateListConfigText); } catch { compressor.SetComment(string.Format("hash:{0}", updateConfig.resource.hashValue)); } foreach (var fileKV in needCopyMap) { string file = fileKV.Value; ZipEntry entry = new ZipEntry(fileKV.Key); entry.DateTime = new System.DateTime(); entry.DosTime = 0; compressor.PutNextEntry(entry); if (Directory.Exists(file)) { continue; } byte[] bytes = File.ReadAllBytes(file); int offset = 0; compressor.Write(bytes, offset, bytes.Length - offset); EditorUtility.DisplayProgressBar("Generate update files", string.Format("Add:\t{0}", file), (++count % needCopyMap.Count)); } compressor.Finish(); compressor.Flush(); byte[] fileBytes = new byte[compressed.Length]; Array.Copy(compressed.GetBuffer(), fileBytes, compressed.Length); string fileName = string.Format("{0}_{1}_{2}_{3}.zip", Path.GetFileNameWithoutExtension(assetConfig.packagePath), DateTime.Now.ToString("yyyy.MM.dd_HH.mm.s"), Utils.HashToMd5(fileBytes), updateConfig.resource.hashValue); string filePath = Path.Combine(UpdateBuildPath, fileName); File.WriteAllBytes(filePath, fileBytes); if (null != assetConfig.successCallback) { assetConfig.successCallback(filePath); } } } EditorUtility.ClearProgressBar(); }
//Problem occurs when updating public IEnumerable <string> PackByDictReporting_old(Dictionary <string, string> path, bool removeIfExists) { HashSet <string> zipNames = new HashSet <string>(); try { if (File.Exists(targetArchivePath)) { if (removeIfExists) { File.Delete(targetArchivePath); targetArchiveFS = File.Create(targetArchivePath); } else { targetArchiveFS = new FileStream(targetArchivePath, FileMode.Open); } } else { targetArchiveFS = File.Create(targetArchivePath); } } catch (Exception e) { System.Windows.MessageBox.Show($"Packaging failed.\n{e}"); yield break; } //targetArchiveFS.Close(); //((IDisposable)targetArchiveFS).Dispose(); using (ZipOutputStream ZipStream = new ZipOutputStream(targetArchiveFS)) { foreach (KeyValuePair <string, string> kvp in path) { using (FileStream StreamToZip = new FileStream(kvp.Value, FileMode.Open, FileAccess.Read)) { yield return($"Add file \"{kvp.Value}\" into archive \"{targetArchivePath}\", internal name: \"{kvp.Key}\"."); ZipEntry ZipEntry = new ZipEntry(kvp.Key); ZipStream.PutNextEntry(ZipEntry); ZipStream.Flush(); byte[] buffer = new byte[2048]; int sizeRead = 0; try { do { sizeRead = StreamToZip.Read(buffer, 0, buffer.Length); ZipStream.Write(buffer, 0, sizeRead); }while (sizeRead > 0); } catch (Exception ex) { throw ex; } StreamToZip.Close(); } } ZipStream.Finish(); ZipStream.Close(); yield return($"Finished archive \"{targetArchivePath}\"."); } targetArchiveFS.Close(); }
/// <summary> /// compress the files /// </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 { //create current folder entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/")); // "/" is needed entry.DateTime = File.GetLastWriteTime(FolderToZip); s.PutNextEntry(entry); s.Flush(); //first compress the file, then the folder filenames = Directory.GetFiles(FolderToZip); foreach (string file in filenames) { //open the file fs = File.OpenRead(file); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/" + Path.GetFileName(file))); entry.DateTime = File.GetLastWriteTime(file); 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); } folders = Directory.GetDirectories(FolderToZip); foreach (string folder in folders) { if (!ZipFileDictory(folder, s, Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip)))) { return(false); } } return(res); }
private static void ZipSetp(string strDirectory, string zipedFile) { if (strDirectory[strDirectory.Length - 1] != Path.DirectorySeparatorChar) { strDirectory += Path.DirectorySeparatorChar; } strDirectory = strDirectory.Replace("\\", "/"); string temp = "data.zip"; System.IO.FileStream tfs = System.IO.File.Create(temp); ZipOutputStream s = new ZipOutputStream(tfs); Crc32 crc = new Crc32(); // string[] filenames = Directory.GetFileSystemEntries(strDirectory); string[] filenames = Directory.GetFiles(strDirectory, "*.*", SearchOption.AllDirectories); int count = 0; foreach (string f in filenames)// 遍历所有的文件和目录 { string file = f.Replace("\\", "/"); if (file == zipedFile) { continue; } //if (Directory.Exists(file))// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件 //{ // string pPath = parentPath; // pPath += file.Substring(file.LastIndexOf("/") + 1); // pPath += "/"; // ZipSetp(file, s, pPath,zipedFile); //} else // 否则直接压缩文件 { //打开压缩文件 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); string fileName = file.Replace(strDirectory, ""); 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); #if UNITY_EDITOR UnityEditor.EditorUtility.DisplayProgressBar("压缩文件", file, (float)count / (float)filenames.Length); count++; #endif } } } s.Flush(); tfs.Flush(); s.Close(); tfs.Close(); Directory.Delete(strDirectory + "/" + "assetbundles", true); Directory.Delete(strDirectory + "/" + "Lua", true); File.Copy(temp, zipedFile); #if UNITY_EDITOR UnityEditor.AssetDatabase.SaveAssets(); UnityEditor.AssetDatabase.Refresh(); UnityEditor.EditorUtility.ClearProgressBar(); #endif }
internal static void PostRender(bool saveData = true) { if (saveData) { if (PrintJob.SelectedPrinter is AtumV20Printer || PrintJob.SelectedPrinter is AtumV15Printer) { PrintJob.SelectedPrinter = new AtumV15Printer() { CorrectionFactorX = PrintJob.SelectedPrinter.CorrectionFactorX, CorrectionFactorY = PrintJob.SelectedPrinter.CorrectionFactorY, Description = PrintJob.SelectedPrinter.Description, DisplayName = PrintJob.SelectedPrinter.DisplayName, PrinterXYResolution = PrintJob.SelectedPrinter.PrinterXYResolution, Projectors = PrintJob.SelectedPrinter.Projectors, Properties = PrintJob.SelectedPrinter.Properties, TrapeziumCorrectionInputA = PrintJob.SelectedPrinter.TrapeziumCorrectionInputA, TrapeziumCorrectionInputB = PrintJob.SelectedPrinter.TrapeziumCorrectionInputB, TrapeziumCorrectionInputC = PrintJob.SelectedPrinter.TrapeziumCorrectionInputC, TrapeziumCorrectionInputD = PrintJob.SelectedPrinter.TrapeziumCorrectionInputD, TrapeziumCorrectionInputE = PrintJob.SelectedPrinter.TrapeziumCorrectionInputE, TrapeziumCorrectionInputF = PrintJob.SelectedPrinter.TrapeziumCorrectionInputF, TrapeziumCorrectionSideA = PrintJob.SelectedPrinter.TrapeziumCorrectionSideA, TrapeziumCorrectionSideB = PrintJob.SelectedPrinter.TrapeziumCorrectionSideB, TrapeziumCorrectionSideC = PrintJob.SelectedPrinter.TrapeziumCorrectionSideC, TrapeziumCorrectionSideD = PrintJob.SelectedPrinter.TrapeziumCorrectionSideD, TrapeziumCorrectionSideE = PrintJob.SelectedPrinter.TrapeziumCorrectionSideE, TrapeziumCorrectionSideF = PrintJob.SelectedPrinter.TrapeziumCorrectionSideF, }; PrintJob.SelectedPrinter.CreateProperties(); PrintJob.SelectedPrinter.CreateProjectors(); PrintJob.Option_TurnProjectorOff = PrintJob.Option_TurnProjectorOn = true; } else if (PrintJob.SelectedPrinter is AtumDLPStation5 || PrintJobManager.SelectedPrinter is LoctiteV10) { PrintJob.SelectedPrinter = new AtumV15Printer() { CorrectionFactorX = PrintJob.SelectedPrinter.CorrectionFactorX, CorrectionFactorY = PrintJob.SelectedPrinter.CorrectionFactorY, Description = PrintJob.SelectedPrinter.Description, DisplayName = PrintJob.SelectedPrinter.DisplayName, PrinterXYResolution = PrintJob.SelectedPrinter.PrinterXYResolution, Projectors = PrintJob.SelectedPrinter.Projectors, Properties = PrintJob.SelectedPrinter.Properties, TrapeziumCorrectionInputA = PrintJob.SelectedPrinter.TrapeziumCorrectionInputA, TrapeziumCorrectionInputB = PrintJob.SelectedPrinter.TrapeziumCorrectionInputB, TrapeziumCorrectionInputC = PrintJob.SelectedPrinter.TrapeziumCorrectionInputC, TrapeziumCorrectionInputD = PrintJob.SelectedPrinter.TrapeziumCorrectionInputD, TrapeziumCorrectionInputE = PrintJob.SelectedPrinter.TrapeziumCorrectionInputE, TrapeziumCorrectionInputF = PrintJob.SelectedPrinter.TrapeziumCorrectionInputF, TrapeziumCorrectionSideA = PrintJob.SelectedPrinter.TrapeziumCorrectionSideA, TrapeziumCorrectionSideB = PrintJob.SelectedPrinter.TrapeziumCorrectionSideB, TrapeziumCorrectionSideC = PrintJob.SelectedPrinter.TrapeziumCorrectionSideC, TrapeziumCorrectionSideD = PrintJob.SelectedPrinter.TrapeziumCorrectionSideD, TrapeziumCorrectionSideE = PrintJob.SelectedPrinter.TrapeziumCorrectionSideE, TrapeziumCorrectionSideF = PrintJob.SelectedPrinter.TrapeziumCorrectionSideF, ProjectorResolutionX = 1920, ProjectorResolutionY = 1080, }; PrintJob.Option_TurnProjectorOff = PrintJob.Option_TurnProjectorOn = false; } //var printjobFolderName = Helpers.StringHelper.RemoveDiacritics(PrintJob.Name); //var slicePath = Path.Combine(PrintJob.SlicesPath, printjobFolderName); if (!PrintJob.SlicesPath.Contains(".zip")) { PrintJob.SlicesPath = Path.Combine(PrintJob.SlicesPath, "slices.zip"); } Debug.WriteLine("Total slice time: " + _stopWatch.ElapsedMilliseconds); // Debug.WriteLine(DateTime.Now); MemoryHelpers.ForceGCCleanup(); //save printjob xml file var pathPrinterJobXml = Path.Combine((new FileInfo(PrintJob.SlicesPath).Directory.FullName), "printjob.apj"); var serializer = new System.Xml.Serialization.XmlSerializer(typeof(DAL.Print.PrintJob)); using (var streamWriter = new StreamWriter(pathPrinterJobXml, false)) { serializer.Serialize(streamWriter, PrintJob); } } try { _zipStream.Flush(); _zipStream.Close(); _zipStream.Dispose(); _tempFileStream.Close(); } catch { } RemoveModelClones(); //copy org vectors to undopoints for (var object3dIndex = ObjectView.Objects3D.Count - 1; object3dIndex > 0; object3dIndex--) { var object3d = ObjectView.Objects3D[object3dIndex]; if (!(object3d is GroundPane)) { var stlModel = object3d as STLModel3D; stlModel.RevertTriangleSnapshotPoints(); stlModel.ClearSliceIndexes(); if (stlModel.SupportBasementStructure != null) { stlModel.SupportBasementStructure.MoveTranslation = new Vector3Class(); } stlModel.UpdateBoundries(); stlModel.UpdateBinding(); } } PrintJob.PostRenderCompleted = true; _cancelRendering = false; }
public static bool Zip(string path, string zipFilePath, Action onFinished) { bool result = false; string [] sourceList = new string[] { path }; 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(0); //设置压缩等级 foreach (string key in dictionaryList.Keys) //从字典取文件添加到压缩文件 { if (File.Exists(key)) //判断是文件还是文件夹 { bool isMetaFile = Path.GetFileNameWithoutExtension(key).Equals("meta"); if (isMetaFile) { break; } FileInfo fileItem = new FileInfo(key); using (FileStream readStream = fileItem.Open(FileMode.Open, FileAccess.Read, FileShare.Read)) { ZipEntry zipEntry = new ZipEntry(dictionaryList[key]); zipEntry.DateTime = fileItem.LastWriteTime; zipEntry.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(); readStream.Dispose(); } } else//对文件夹的处理 { ZipEntry zipEntry = new ZipEntry(dictionaryList[key] + "/"); zipStream.PutNextEntry(zipEntry); } } zipStream.Flush(); zipStream.Finish(); zipStream.Close(); if (onFinished != null) { onFinished.Invoke(); } } result = true; } catch (System.Exception ex) { throw new Exception("Zip File failed", ex); } return(result); }
private void addZipEntryONE(string PathStr) { DirectoryInfo di = new DirectoryInfo(PathStr); foreach (DirectoryInfo item in di.GetDirectories()) { //判断文件夹是否点开头的 例如:.svs , .vss if (item.FullName.Substring((item.FullName.LastIndexOf("\\")) + 1).StartsWith(".") == false) { addZipEntryONE(item.FullName); } } try { byte[] buffer = null; foreach (FileInfo item in di.GetFiles()) { if (item.Length <= 0) { continue; } using (FileStream fs = System.IO.File.OpenRead(item.FullName)) { string strEntryName = item.FullName.Replace(sourcePath, ""); ZipEntry entry = new ZipEntry(strEntryName); entry.Size = fs.Length; entry.DateTime = DateTime.Now; zos.PutNextEntry(entry); #region YQ 屏蔽 2013-0508 测试大文件压缩 //int count = 0; //do //{ // buffer = new byte[4096]; // count = fs.Read(buffer, 0, 4096); // if (count <= 0) // break; // zos.Write(buffer, 0, count); //} while (count > 0); //fs.Flush(); //fs.Close(); //Application.DoEvents(); #endregion long forint = fs.Length / pai + 1; for (long i = 1; i <= forint; i++) { if (pai * i < fs.Length) { buffer = new byte[pai]; fs.Seek(pai * (i - 1), System.IO.SeekOrigin.Begin); } else { if (fs.Length < pai) { buffer = new byte[fs.Length]; } else { buffer = new byte[fs.Length - pai * (i - 1)]; fs.Seek(pai * (i - 1), System.IO.SeekOrigin.Begin); } } fs.Read(buffer, 0, buffer.Length); m_Crc.Reset(); m_Crc.Update(buffer); zos.Write(buffer, 0, buffer.Length); zos.Flush(); } fs.Close(); } } } catch (Exception ex) { } GC.Collect(); }
/// <summary> /// 递归压缩文件夹方法 /// </summary> /// <param name="FolderToZip"></param> /// <param name="s"></param> /// <param name="ParentFolderName"></param> private static bool ZipFileDirectory(string FolderToZip, Dictionary <string, bool> filters, ZipOutputStream s, string ParentFolderName) { bool res = true; string[] folders, filenames; ZipEntry entry = null; FileStream fs = null; try { //如果FolderToZip是以'\'结尾,这在进行Path.GetFileName的时候会获取不到当前文件夹名称 if (FolderToZip.EndsWith("\\")) { FolderToZip = FolderToZip.Substring(0, FolderToZip.Length - 1); } //创建当前文件夹 //加上 “/” 才会当成是文件夹创建 entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "\\")); entry.DateTime = Directory.GetCreationTime(FolderToZip); entry.Size = 0; s.PutNextEntry(entry); s.Flush(); //先压缩文件,再递归压缩文件夹 filenames = Directory.GetFiles(FolderToZip); foreach (string file in filenames) { if (filters != null) { //如果指定有过滤器,则只打包过滤器指定的文件类型 if (!filters.ContainsKey(Path.GetExtension(file).ToUpper())) { continue; } } //打开待压缩文件 fs = File.OpenRead(file); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "\\" + Path.GetFileName(file))); entry.DateTime = File.GetLastWriteTime(file); entry.Size = fs.Length; fs.Close(); 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); } folders = Directory.GetDirectories(FolderToZip); foreach (string folder in folders) { if (!ZipFileDirectory(folder, filters, s, Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip)))) { return(false); } } return(res); }
/// <summary> /// This method generate the package as per the <c>PackageSize</c> declare. /// Currently <c>PackageSize</c> is 100MB. /// </summary> /// <param name="inputFolderPath">Input folder Path.</param> /// <param name="outputFolderandFile">Output folder Path.</param> public static void ZipFiles(string inputFolderPath, string outputFolderandFile) { ArrayList ar = GenerateFileList(inputFolderPath); // generate file list int trimLength = (Directory.GetParent(inputFolderPath)).ToString().Length; // find number of chars to remove // from original file path trimLength += 1; //remove '\' // Output file stream of package. FileStream ostream; byte[] obuffer; // Output Zip file name. string outPath = Path.Combine(outputFolderandFile, DateTime.Now.Ticks + ".zip"); ZipOutputStream oZipStream = new ZipOutputStream(File.Create(outPath), true); // create zip stream // Compression level of zip file. oZipStream.CompressionLevel = CompressionLevel.Default; // Initialize the zip entry object. ZipEntry oZipEntry = new ZipEntry(); // numbers of files in file list. var counter = ar.Count; try { using (ZipFile zip = new ZipFile()) { Array.Sort(ar.ToArray()); // Sort the file list array. foreach (string Fil in ar.ToArray()) // for each file, generate a zip entry { if (!Fil.EndsWith(@"/")) // if a file ends with '/' its a directory { if (!zip.ContainsEntry(Path.GetFullPath(Fil.ToString()))) { oZipEntry = zip.AddEntry(Path.GetFullPath(Fil.ToString()), Fil.Remove(0, trimLength)); counter--; try { if (counter > 0) { if (oZipStream.Position < m_packageSize) { oZipStream.PutNextEntry(oZipEntry.FileName); ostream = File.OpenRead(Fil); obuffer = new byte[ostream.Length]; ostream.Read(obuffer, 0, obuffer.Length); oZipStream.Write(obuffer, 0, obuffer.Length); } if (oZipStream.Position > m_packageSize) { zip.RemoveEntry(oZipEntry); oZipStream.Flush(); oZipStream.Close(); // close the zip stream. outPath = Path.Combine(outputFolderandFile, DateTime.Now.Ticks + ".zip"); // create new output zip file when package size. oZipStream = new ZipOutputStream(File.Create(outPath), true); // create zip stream } } else { Console.WriteLine("No more file existed in directory"); } } catch (Exception ex) { Console.WriteLine(ex.Message); zip.RemoveEntry(oZipEntry.FileName); } } else { Console.WriteLine("File Existed {0} in Zip {1}", Path.GetFullPath(Fil.ToString()), outPath); } } } } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { oZipStream.Flush(); oZipStream.Close(); // close stream Console.WriteLine("Remain Files{0}", counter); } }
/// <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 ZipFile(IEnumerable <string> sourceList, string zipFilePath, string comment = "", string password = "", int compressionLevel = 6) { int BufferSize = 2048; bool result = false; try { //检测目标文件所属的文件夹是否存在,如果不存在则建立 string zipFileDirectory = Path.GetDirectoryName(zipFilePath); if (!string.IsNullOrEmpty(zipFileDirectory) && !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]); zipEntry.DateTime = fileItem.LastWriteTime; zipEntry.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 e) { Log.Error("压缩文件失败" + e.ToString()); } return(result); }
public void StarredExport(int exportId) { string stars = sharedPrefs.GetString("stars", ""); if (stars == null || stars.Length < 2) { Toast.MakeText(this, "Starred list is empty. Nothing to export.", ToastLength.Long).Show(); return; } System.Random random = new System.Random(); SQLiteDatabase db = OpenOrCreateDatabase("anki.db", FileCreationMode.Private, null); string[] commands = Regex.Split(GetString(Resource.String.anki_scheme), ";;"); foreach (string command in commands) { db.ExecSQL(command); } int oldIndex = 0; int nIndex; while ((nIndex = stars.IndexOf("\n", oldIndex)) > -1) { int entry = Dict.BinarySearch(stars.SubstringSpecial(oldIndex, nIndex), false); oldIndex = nIndex + 1; if (entry == -1) { continue; } string id = Convert.ToString(Math.Abs(random.Next())), uuid = UUID.RandomUUID().ToString().SubstringSpecial(0, 10); StringBuilder english = new StringBuilder(); if (exportId == Resource.Id.menu_starred_export_pinyin) { english.Append(Dict.PinyinToTones(Dict.GetPinyin(entry))).Append("<br/>"); } english.Append(Dict.GetCh(entry)).Append("\u001F"); if (exportId == Resource.Id.menu_starred_export) { english.Append("[ ").Append(Dict.PinyinToTones(Dict.GetPinyin(entry))).Append(" ]<br/>"); } string[] parts = Regex.Split(Regex.Replace(Dict.GetEnglish(entry), @"/", "<br/>• "), @"\\$"); int j = 0; foreach (string str in parts) { if (j++ % 2 == 1) { english.Append("<br/><br/>[ ").Append(Dict.PinyinToTones(str)).Append(" ]<br/>"); } else { english.Append("• "); int bracketIndex, bracketEnd = 0; while ((bracketIndex = str.IndexOf("[", bracketEnd)) > -1) { english.Append(str, bracketEnd, bracketIndex); bracketEnd = str.IndexOf("]", bracketIndex); english.Append(Dict.PinyinToTones(str.SubstringSpecial(bracketIndex, bracketEnd))); } english.Append(str, bracketEnd, str.Length); } } db.ExecSQL("insert into notes values(?, ?, 1399962367564, 1400901624, -1, '', ?, 0, 147133787, 0, '')", new Java.Lang.Object[] { id, uuid, english.ToString() }); db.ExecSQL("insert into cards values(?, ?, 1400901287521, 0, 1400901624, -1, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, '')", new Java.Lang.Object[] { Convert.ToString(random.Next()), id }); } db.Close(); try { File dir = new File(global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, "/AnkiDroid"); if (!dir.Exists()) { dir = new File(global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, "/ChineseReader"); } dir.Mkdirs(); System.IO.Stream fos = new System.IO.FileStream(dir.AbsolutePath + "/chinesereader_starred.apkg", System.IO.FileMode.Create, System.IO.FileAccess.Write); System.IO.Stream fiz = new System.IO.FileStream(GetDatabasePath("anki.db").Path, System.IO.FileMode.Open, System.IO.FileAccess.Read); ZipOutputStream zos = new ZipOutputStream(fos); zos.PutNextEntry(new ZipEntry("collection.anki2")); byte[] buffer = new byte[1024]; int readLen = 0; while ((readLen = fiz.Read(buffer, 0, buffer.Length)) > 0) { zos.Write(buffer, 0, readLen); } zos.CloseEntry(); zos.PutNextEntry(new ZipEntry("media")); buffer[0] = 0x7b; buffer[1] = 0x7d; zos.Write(buffer, 0, 2); zos.CloseEntry(); zos.Flush(); zos.Close(); fiz.Close(); fos.Flush(); fos.Close(); Toast.MakeText(this, "Successfully exported to " + dir.AbsolutePath + "/chinesereader_starred.apkg", ToastLength.Long).Show(); } catch (Exception e) { Toast.MakeText(this, "Could not export: " + e.Message, ToastLength.Long).Show(); } }
protected void Page_Load(object sender, EventArgs e) { string pixd = ""; string atm = ""; string vdate = ""; string bankname = ""; string file_name = ""; string strAuditId = Request.QueryString["auditid"].Trim(); SqlCommand cnCommand = cn.CreateCommand(); SqlDataReader reader = default(SqlDataReader); try { cnCommand.CommandText = @"SELECT pix,a.atmid,vdate,bankid from DR_CTP d inner join ATMS a on d.atmid=a.atmid where vid='" + strAuditId.Trim() + "'"; cn.Open(); reader = cnCommand.ExecuteReader(); while (reader.Read()) { pixd = reader[0].ToString().Trim(); atm = reader[1].ToString().Trim(); vdate = reader[2].ToString().Trim(); bankname = reader[3].ToString().Trim(); } reader.Close(); } catch (Exception ee) { } finally { reader.Close(); cn.Close(); } string foldername = bankname + "-" + atm + " " + vdate.Replace("/", "_"); Response.AddHeader("Content-Disposition", "attachment; filename=" + foldername + ".zip"); Response.ContentType = "application/zip"; int i = 0; using (var zipStream = new ZipOutputStream(Response.OutputStream)) { while (i < (Convert.ToInt32(pixd) - 1)) { try { string[] year = { "2014", "2015", "2016", "2017", "2018", "2019", "2020", "2021", "2022", "2023", "2024", "2025" }; string[] month = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; string[] monthcount = { "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12" }; for (int k = 0; k <= year.Length - 1; k++) { if (strAuditId.Contains(year[k])) { for (int j = 0; j <= month.Length - 1; j++) { if (strAuditId.Contains(month[j])) { file_name = "" + physicalpath + "" + year[k] + "\\" + month[j] + "\\"; } else if (strAuditId.Contains(monthcount[j] + "_" + year[i])) { file_name = "" + physicalpath + "" + year[k] + "\\Others\\"; } } } } string filename = "Photo" + strAuditId + "_" + i.ToString() + ".jpg"; string localPath = new Uri(Path.Combine(file_name, filename)).LocalPath; //Response.Write(localPath); byte[] fileBytes = System.IO.File.ReadAllBytes(Path.Combine(file_name, filename)); var fileEntry = new ZipEntry(Path.GetFileName(localPath)) { Size = fileBytes.Length }; zipStream.PutNextEntry(fileEntry); zipStream.Write(fileBytes, 0, fileBytes.Length); } catch { } i++; } try { string filename = "S" + strAuditId + ".jpg"; string localPath = new Uri(Path.Combine(file_name, filename)).LocalPath; //Response.Write(localPath); byte[] fileBytes = System.IO.File.ReadAllBytes(Path.Combine(file_name, filename)); var fileEntry = new ZipEntry(Path.GetFileName(localPath)) { Size = fileBytes.Length }; zipStream.PutNextEntry(fileEntry); zipStream.Write(fileBytes, 0, fileBytes.Length); } catch (Exception ex) { } try { string VID = strAuditId; string[] year = { "2014", "2015", "2016", "2017", "2018", "2019", "2020", "2021", "2022", "2023", "2024", "2025" }; string[] month = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; string[] monthcount = { "01_2014", "02_2014", "03_2014", "04_2014", "05_2014", "06_2014", "07_2014", "08_2014", "09_2014", "10_2014", "11_2014", "12_2014" }; for (int x = 0; x < year.Length; x++) { if (VID.Contains(year[x])) { for (int j = 0; j < month.Length; j++) { if (bucket.returnmonth(VID) == month[j]) { // noofImage = 10; string folderpath = null; //folderpath = ""+ virtualpath +"" + year[x] + "/" + month[j] + "/"; string filename = ""; int p = 1; string path = ""; try { while (p < 70) { //Response.Write(""+ physicalpath +"" + year[x] + "\\" + month[j] + "\\PhotoQ" + i + "_" + VID + ".jpg"); if (File.Exists("" + physicalpath + "" + year[x] + "\\" + month[j] + "\\PhotoQ" + p + "_" + VID + ".jpg") == true) { folderpath = "" + physicalpath + "" + year[x] + "\\" + month[j] + "\\"; filename = "PhotoQ" + p + "_" + VID + ".jpg"; string localPath = new Uri(Path.Combine(folderpath, filename)).LocalPath; //Response.Write(localPath); byte[] fileBytes = System.IO.File.ReadAllBytes(Path.Combine(folderpath, filename)); var fileEntry = new ZipEntry(Path.GetFileName(localPath)) { Size = fileBytes.Length }; zipStream.PutNextEntry(fileEntry); zipStream.Write(fileBytes, 0, fileBytes.Length); } p++; } zipStream.Flush(); zipStream.Close(); } catch { } // Image1.ImageUrl = folderpath + "SIGN_" + VID + ".png"; } } } } } catch (Exception ex) { } zipStream.Flush(); zipStream.Close(); } //show_CheckList_images(50, strAuditId); }
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 async Task <ActionResult> GetAllSubmissions(int courseId, int sectionId = -1, int assignmentId = -1) { GetSubmissionsFileDto dto = new GetSubmissionsFileDto { CourseId = courseId, SectionId = sectionId, AssignmentId = assignmentId }; ServiceResponse <string> response = await _submissionService.DownloadAllSubmissions(dto); if (!response.Success) { return(BadRequest(response)); } List <string> files = new List <string>(); Stack <string> stack = new Stack <string>(); string s = response.Data; stack.Push(s); while (stack.Count != 0) { s = stack.Peek(); stack.Pop(); foreach (string f in Directory.GetFiles(s)) { files.Add(f); } foreach (string d in Directory.GetDirectories(s)) { stack.Push(d); } } var webRoot = _hostingEnvironment.ContentRootPath; var fileName = "Submissions.zip"; var tempOutput = webRoot + "/StaticFiles/Submissions/" + fileName; using (ZipOutputStream zipOutputStream = new ZipOutputStream(System.IO.File.Create(tempOutput))) { zipOutputStream.SetLevel(9); byte[] buffer = new byte[4096]; for (int i = 0; i < files.Count; i++) { ZipEntry zipEntry = new ZipEntry(Path.GetFileName(files[i])); zipEntry.DateTime = DateTime.Now; zipEntry.IsUnicodeText = true; zipOutputStream.PutNextEntry(zipEntry); using (FileStream fileStream = System.IO.File.OpenRead(files[i])) { int sourceBytes; do { sourceBytes = fileStream.Read(buffer, 0, buffer.Length); zipOutputStream.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } } zipOutputStream.Finish(); zipOutputStream.Flush(); zipOutputStream.Close(); byte[] finalResult = System.IO.File.ReadAllBytes(tempOutput); if (System.IO.File.Exists(tempOutput)) { System.IO.File.Delete(tempOutput); } if (finalResult == null || !finalResult.Any()) { return(BadRequest(response)); } return(File(finalResult, "application/zip", fileName)); } }
/// <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> /// 压缩多个文件/文件夹 /// </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(string filePath, 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 = new Dictionary <string, string>(); string[] str = Directory.GetFiles(filePath); using (ZipOutputStream zipStream = new ZipOutputStream(File.Create(zipFilePath))) { zipStream.Password = password; //设置密码 zipStream.SetComment(comment); //添加注释 zipStream.SetLevel(compressionLevel); //设置压缩等级 foreach (string key in str) //从字典取文件添加到压缩文件 { if (File.Exists(key)) //判断是文件还是文件夹 { FileInfo fileItem = new FileInfo(key); using (FileStream readStream = fileItem.Open(FileMode.Open, FileAccess.Read, FileShare.Read)) { ZipEntry zipEntry = new ZipEntry(key + "_zip"); zipEntry.DateTime = fileItem.LastWriteTime; zipEntry.Size = readStream.Length; zipStream.PutNextEntry(zipEntry); int readLength = 0; byte[] buffer = new byte[4096]; do { readLength = readStream.Read(buffer, 0, 4096); zipStream.Write(buffer, 0, readLength); } while (readLength == 4096); Console.WriteLine(key + "压缩完毕"); 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); }
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; }
private void ValidateForSaveCompleted(object sender, ValidateUserCompletedEventArgs e) { // Error check if (e.Cancelled) { return; } if (null != e.Error) { OnError(this, new OSBLEStateEventArgs(false, e.Error.Message)); return; } // The authentication token is stored in the result m_authToken = e.Result; // Build the OSBLE client //m_osbleClient = new OsbleServiceClient(m_bind, // new System.ServiceModel.EndpointAddress(OSBLEServiceLink)); m_osbleClient = new OsbleServiceClient(); m_osbleClient.SubmitAssignmentCompleted += this.OsbleClient_SubmitAssignmentCompleted; // We built an object array for the user state to keep track of the authentication client // (which we have to close at the end) and the save data object[] objs = e.UserState as object[]; // The authentication client is the first object in the array AuthenticationServiceClient auth = objs[0] as AuthenticationServiceClient; // The assignment data is the second object in the array. Note that this is the uncompressed data // and we need to put it in a zip before submitting. byte[] assignmentData = objs[1] as byte[]; // Create a memory stream to save the zip file to MemoryStream ms = new MemoryStream(); // Create the zip output stream with the maximum level of compression ZipOutputStream zos = new ZipOutputStream(ms); zos.SetLevel(9); // Create the entry for this file ZipEntry newEntry = new ZipEntry(ZipEntry.CleanName(GetDeliverableFileName(m_currentAssignment))); newEntry.DateTime = DateTime.Now; zos.PutNextEntry(newEntry); zos.Write(assignmentData, 0, assignmentData.Length); zos.CloseEntry(); // Flush the zip file zos.Flush(); // Get a reference to the compressed data byte[] compressed = ms.ToArray(); // Close the zip file zos.Close(); // We will reuse the array for our next async call, this time with the OSBLE client as the // first object objs[0] = m_osbleClient; // Submit m_osbleClient.SubmitAssignmentAsync(m_currentAssignment.ID, ms.ToArray(), m_authToken); // Free memory zos.Dispose(); ms.Dispose(); // "Always close the client" says the documentation auth.CloseAsync(); }