/// <summary> /// 压缩单个文件 /// </summary> /// <param name="fileToZip">要压缩的文件</param> /// <param name="zipedFile">压缩后的文件</param> /// <param name="compressionLevel">压缩等级</param> /// <param name="blockSize">每次写入大小</param> public void ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize) { //如果文件没有找到,则报错 if (!System.IO.File.Exists(fileToZip)) { throw new System.IO.FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!"); } using (System.IO.FileStream ZipFile = System.IO.File.Create(zipedFile)) { using (ZipOutputStream ZipStream = new ZipOutputStream(ZipFile)) { using (System.IO.FileStream StreamToZip = new System.IO.FileStream(fileToZip, System.IO.FileMode.Open, System.IO.FileAccess.Read)) { string fileName = fileToZip.Substring(fileToZip.LastIndexOf("\\") + 1); ZipEntry ZipEntry = new ZipEntry(fileName); ZipStream.PutNextEntry(ZipEntry); ZipStream.SetLevel(compressionLevel); byte[] buffer = new byte[blockSize]; int sizeRead = 0; try { do { sizeRead = StreamToZip.Read(buffer, 0, buffer.Length); ZipStream.Write(buffer, 0, sizeRead); } while (sizeRead > 0); } catch (System.Exception ex) { throw ex; } StreamToZip.Close(); } ZipStream.Finish(); ZipStream.Close(); } ZipFile.Close(); } }
/// <summary> /// 压缩单个文件 /// </summary> /// <param name="fileToZip">要进行压缩的文件名</param> /// <param name="zipedFile">压缩后生成的压缩文件名</param> /// <param name="compressionLevel">压缩级别</param> public void ZipFile(string fileToZip, string zipedFile, int compressionLevel = 9) { //如果文件没有找到,则报错 if (!File.Exists(fileToZip)) { throw new System.IO.FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!"); } using (FileStream fs = File.OpenRead(fileToZip)) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); fs.Close(); using (FileStream ZipFile = File.Create(zipedFile)) { using (ZipOutputStream ZipStream = new ZipOutputStream(ZipFile)) { string fileName = fileToZip.Substring(fileToZip.LastIndexOf("\\") + 1); ZipEntry ZipEntry = new ZipEntry(fileName); ZipStream.PutNextEntry(ZipEntry); ZipStream.SetLevel(compressionLevel); ZipStream.Write(buffer, 0, buffer.Length); ZipStream.Finish(); ZipStream.Close(); } } } }
/// <summary> /// 压缩多层目录 /// </summary> /// <param name="strDirectory">The directory.</param> /// <param name="zipedFile">The ziped file.</param> public void ZipFileDirectory(string strDirectory, string zipedFile) { using (System.IO.FileStream ZipFile = System.IO.File.Create(zipedFile)) { using (ZipOutputStream s = new ZipOutputStream(ZipFile)) { ZipSetp(strDirectory, s, ""); } } }
/// <summary> /// 递归遍历目录 /// </summary> /// <param name="strDirectory">The directory.</param> /// <param name="s">The ZipOutputStream Object.</param> /// <param name="parentPath">The parent path.</param> private void ZipSetp(string strDirectory, ZipOutputStream s, string parentPath) { if (strDirectory[strDirectory.Length - 1] != Path.DirectorySeparatorChar) { strDirectory += Path.DirectorySeparatorChar; } CRC32 crc = new CRC32(); string[] filenames = Directory.GetFileSystemEntries(strDirectory); foreach (string file in filenames)// 遍历所有的文件和目录 { if (Directory.Exists(file))// 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件 { string pPath = parentPath; pPath += file.Substring(file.LastIndexOf("\\") + 1); pPath += "\\"; ZipSetp(file, s, pPath); } 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); 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); } } } }
public int WriteDataToZipFile(string zipPath, CancellationToken cancellationToken, Action<string, double> progressCallback) { // create a zip file to hold all data #if __ANDROID__ ZipOutputStream zipFile = null; #elif __IOS__ ZipArchive zipFile = null; #endif // write all data to separate JSON files. zip files for convenience. string directory = null; Dictionary<string, StreamWriter> datumTypeFile = new Dictionary<string, StreamWriter>(); try { string directoryName = Protocol.Name + "_Data_" + DateTime.UtcNow.ToShortDateString() + "_" + DateTime.UtcNow.ToShortTimeString(); directoryName = new Regex("[^a-zA-Z0-9]").Replace(directoryName, "_"); directory = Path.Combine(SensusServiceHelper.SHARE_DIRECTORY, directoryName); if (Directory.Exists(directory)) Directory.Delete(directory, true); Directory.CreateDirectory(directory); if (progressCallback != null) progressCallback("Gathering data...", 0); int totalDataCount = 0; foreach (Tuple<string, string> datumTypeLine in GetDataLinesToWrite(cancellationToken, progressCallback)) { string datumType = datumTypeLine.Item1; string line = datumTypeLine.Item2; StreamWriter file; if (datumTypeFile.TryGetValue(datumType, out file)) file.WriteLine(","); else { file = new StreamWriter(Path.Combine(directory, datumType + ".json")); file.WriteLine("["); datumTypeFile.Add(datumType, file); } file.Write(line); ++totalDataCount; } // close all files foreach (StreamWriter file in datumTypeFile.Values) { file.Write(Environment.NewLine + "]"); file.Close(); } cancellationToken.ThrowIfCancellationRequested(); if (progressCallback != null) progressCallback("Compressing data...", 0); #if __ANDROID__ directoryName += '/'; zipFile = new ZipOutputStream(new FileStream(zipPath, FileMode.Create, FileAccess.Write)); zipFile.PutNextEntry(new ZipEntry(directoryName)); int dataWritten = 0; foreach (string path in Directory.GetFiles(directory)) { // start json file for data of current type zipFile.PutNextEntry(new ZipEntry(directoryName + Path.GetFileName(path))); using (StreamReader file = new StreamReader(path)) { string line; while ((line = file.ReadLine()) != null) { if (progressCallback != null && totalDataCount >= 10 && (dataWritten % (totalDataCount / 10)) == 0) progressCallback(null, dataWritten / (double)totalDataCount); cancellationToken.ThrowIfCancellationRequested(); zipFile.Write(file.CurrentEncoding.GetBytes(line + Environment.NewLine)); if (line != "[" && line != "]") ++dataWritten; } } zipFile.CloseEntry(); System.IO.File.Delete(path); } // close entry for directory zipFile.CloseEntry(); #elif __IOS__ zipFile = new ZipArchive(); zipFile.CreateZipFile(zipPath); zipFile.AddFolder(directory, null); #endif if (progressCallback != null) progressCallback(null, 1); return totalDataCount; } finally { // ensure that zip file is closed. try { if (zipFile != null) { #if __ANDROID__ zipFile.Close(); #elif __IOS__ zipFile.CloseZipFile(); #endif } } catch (Exception) { } // ensure that all temporary files are closed/deleted. foreach (string datumType in datumTypeFile.Keys) { try { datumTypeFile[datumType].Close(); } catch (Exception) { } } try { Directory.Delete(directory, true); } catch (Exception) { } } }