protected override void OnClosing(CancelEventArgs e) { if (isBusy) { var result = MessageBox.Show("Backup still in progress. Are you sure you want to quit?\nAny unfinished backups may be corrupted or incomplete.", "Quit", MessageBoxButton.YesNo); if (result == MessageBoxResult.No) { e.Cancel = true; } else { try { zipStream?.Close(); } catch (Exception ex) { Debug.WriteLine(ex.Message); } finally { File.Delete(tempFileName); pBar.IsIndeterminate = isBusy = false; e.Cancel = false; } } } base.OnClosing(e); }
private async Task ScanFiles(string filename) { tempFileName = $"{ TEMP_FOLDER }\\" + filename.Substring(filename.IndexOf(selectedSaveName.Trim() + "_"), filename.Length - filename.IndexOf(selectedSaveName.Trim() + "_")); var fsOut = File.Create(tempFileName); pBar.IsIndeterminate = isBusy = true; zipStream = new ZipOutputStream(fsOut); zipStream.SetLevel(5); //0-9, 9 being the highest level of compression int folderOffset = (MC_SAVES_FOLDER + selectedSaveName).Length + ((MC_SAVES_FOLDER + selectedSaveName).EndsWith("\\") ? 0 : 1); await Task.Run(() => CompressFolder((MC_SAVES_FOLDER + selectedSaveName), zipStream, folderOffset)); zipStream.IsStreamOwner = true; // Makes the Close also Close the underlying stream zipStream?.Close(); pBar.IsIndeterminate = isBusy = false; if (File.Exists(tempFileName)) { File.Move(tempFileName, filename); } MessageBox.Show("Export complete."); BackupBtn.Content = "Start Backup"; }
public static bool ZipFilesAndChildFiles(string folderPath, string zipFileName) { ZipOutputStream zipStream = null; try { if (!Directory.Exists(folderPath)) { Console.WriteLine("Cannot find directory '{0}'", folderPath); return(false); } if (folderPath[folderPath.Length - 1] != System.IO.Path.DirectorySeparatorChar) { folderPath += System.IO.Path.DirectorySeparatorChar; } string tmp = folderPath.Substring(0, folderPath.LastIndexOf("\\")); string entryFolder = tmp.Substring(tmp.LastIndexOf("\\") + 1); if (!zipFileName.ToLower().EndsWith(ConstHelper.ZIPExtension)) { zipFileName += ConstHelper.ZIPExtension; } zipStream = new ZipOutputStream(File.Create(zipFileName)); zipStream.SetLevel(9); ZipDirectory(folderPath, zipStream, entryFolder); return(true); } catch (Exception ex) { throw ex; } finally { zipStream?.Finish(); zipStream?.Close(); } }
/// <summary> /// 压缩多个文件/文件夹 /// </summary> /// <param name="sourceList">源文件/文件夹路径列表</param> /// <param name="zipFilePath">压缩文件路径</param> /// <param name="comment">注释信息</param> /// <param name="password">压缩密码</param> /// <param name="compressionLevel">压缩等级,范围从0到9,可选,默认为6</param> /// <returns></returns> public static bool CompressFile(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); }
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 }
void UpdateSettingConf(string path) { byte[] setting_buf = CreateSettingConf(); using (ZipInputStream inputStream = new ZipInputStream(File.Open(path, FileMode.Open))) { using (ZipOutputStream outputStream = new ZipOutputStream(File.Create(path + ".temp"))) { ZipEntry entry; try { while ((entry = inputStream.GetNextEntry()) != null) { outputStream.SetLevel(6); if (entry.Name.IndexOf("Setting.conf", StringComparison.CurrentCultureIgnoreCase) >= 0) { Crc32 crc = new Crc32(); //打开压缩文件 ZipEntry new_entry = new ZipEntry(entry.Name); new_entry.DateTime = DateTime.Now; crc.Reset(); crc.Update(setting_buf); entry.Crc = crc.Value; outputStream.PutNextEntry(new_entry); outputStream.Write(setting_buf, 0, setting_buf.Length); } else { if (entry.IsDirectory) { ZipEntry new_entry = new ZipEntry(entry.Name); new_entry.DateTime = DateTime.Now; outputStream.PutNextEntry(entry); } else { byte[] buffer = new byte[entry.Size]; inputStream.Read(buffer, 0, buffer.Length); Crc32 crc = new Crc32(); //打开压缩文件 ZipEntry new_entry = new ZipEntry(entry.Name); new_entry.DateTime = DateTime.Now; crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; outputStream.PutNextEntry(new_entry); outputStream.Write(buffer, 0, buffer.Length); } } } } finally { outputStream.Finish(); outputStream.Close(); } } } File.Copy(path + ".temp", path, true); File.Delete(path + ".temp"); }
private void Worker() { Interface.Oxide.LogInfo("[DropBox] Initialized"); _Settings = _DataFileSystem.ReadObject <Settings>(Path.Combine(_ConfigDirectory, "DropBox")); if (_Settings.FileList == null) { _Settings = new Settings(); _Settings.BackupOxideConfig = true; _Settings.BackupOxideData = true; _Settings.BackupOxideLang = true; _Settings.BackupOxideLogs = true; _Settings.BackupOxidePlugins = true; _Settings.FileList = new List <string>(); _Settings.UserToken = ""; _Settings.UserSecret = ""; _Settings.BackupName = "Oxide DropBox Extension"; _Settings.BackupInterval = 3600; _Settings.DropboxApi = new Dictionary <string, string>(); _Settings.DropboxApi.Add("DropboxAppKey", ""); _Settings.DropboxApi.Add("DropboxAppSecret", ""); _DataFileSystem.WriteObject <Settings>(Path.Combine(_ConfigDirectory, "DropBox"), _Settings); } if (_Settings.BackupInterval < 3600) { Interface.Oxide.LogError("[DropBox] You can't set backup interval lower than 1 hour."); _Settings.BackupInterval = 3600; _DataFileSystem.WriteObject <Settings>(Path.Combine(_ConfigDirectory, "DropBox"), _Settings); } if ((string.IsNullOrEmpty(_Settings.DropboxApi["DropboxAppKey"])) || (string.IsNullOrEmpty(_Settings.DropboxApi["DropboxAppSecret"]))) { _running = false; Interface.Oxide.LogWarning("[DropBox] To able to use DropBox Extension you need to set DropboxAppKey and DropboxAppSecret in config file."); } if (_running) { DropboxServiceProvider dropboxServiceProvider = new DropboxServiceProvider(_Settings.DropboxApi["DropboxAppKey"], _Settings.DropboxApi["DropboxAppSecret"], AccessLevel.Full); OAuthToken oauthAccessToken = null; bool Authorized = false; IDropbox dropbox = null; do { if ((_running) && (string.IsNullOrEmpty(_Settings.UserToken) || string.IsNullOrEmpty(_Settings.UserSecret))) { Interface.Oxide.LogInfo("[DropBox] Getting request token..."); OAuthToken oauthToken = dropboxServiceProvider.OAuthOperations.FetchRequestToken(null, null); Interface.Oxide.LogInfo("[DropBox] Done"); OAuth1Parameters parameters = new OAuth1Parameters(); string authenticateUrl = dropboxServiceProvider.OAuthOperations.BuildAuthenticateUrl(oauthToken.Value, parameters); Interface.Oxide.LogInfo("[DropBox] Redirect user for authorization"); Interface.Oxide.LogInfo("[DropBox] {0}", authenticateUrl); while ((_running) && (Authorized == false)) { try { AuthorizedRequestToken requestToken = new AuthorizedRequestToken(oauthToken, null); oauthAccessToken = dropboxServiceProvider.OAuthOperations.ExchangeForAccessToken(requestToken, null); Authorized = true; _Settings.UserToken = oauthAccessToken.Value; _Settings.UserSecret = oauthAccessToken.Secret; _DataFileSystem.WriteObject <Settings>(Path.Combine(_ConfigDirectory, "DropBox"), _Settings); } catch { Thread.Sleep(5000); } } } else if (_running) { oauthAccessToken = new OAuthToken(_Settings.UserToken, _Settings.UserSecret); } if (_running) { try { Interface.Oxide.LogInfo("[DropBox] Authorizing"); dropbox = dropboxServiceProvider.GetApi(oauthAccessToken.Value, oauthAccessToken.Secret); Interface.Oxide.LogInfo("[DropBox] Authorization Succeed"); Authorized = true; } catch { Interface.Oxide.LogWarning("[DropBox] Authorization Failed"); _Settings.UserToken = ""; _Settings.UserSecret = ""; _DataFileSystem.WriteObject <Settings>(Path.Combine(_ConfigDirectory, "DropBox"), _Settings); Authorized = false; } } } while ((_running) && (Authorized == false)); if ((_running) && (dropbox != null) && (Authorized == true)) { DropboxProfile profile = dropbox.GetUserProfile(); Interface.Oxide.LogInfo("[DropBox] Current Dropbox User : {0}({1})", profile.DisplayName, profile.Email); DateTime NextUpdate = DateTime.Now.AddSeconds(60); Interface.Oxide.LogInfo("[DropBox] First Backup : {0}", NextUpdate.ToString()); while (_running) { if (DateTime.Now < NextUpdate) { Thread.Sleep(1000); } else { string BackUpRoot = Path.Combine(Interface.Oxide.RootDirectory, "OxideExtBackup"); string OxideBackUpRoot = Path.Combine(BackUpRoot, "Oxide"); string FileBackUpRoot = Path.Combine(BackUpRoot, "Files"); Directory.CreateDirectory(BackUpRoot); DirectoryInfo OxideExtBackup = new DirectoryInfo(BackUpRoot); foreach (FileInfo file in OxideExtBackup.GetFiles()) { file.Delete(); } foreach (DirectoryInfo subDirectory in OxideExtBackup.GetDirectories()) { subDirectory.Delete(true); } Directory.CreateDirectory(OxideBackUpRoot); Directory.CreateDirectory(FileBackUpRoot); if (_Settings.BackupOxideConfig) { DirectoryCopy(Interface.Oxide.ConfigDirectory, Path.Combine(OxideBackUpRoot, "config"), true); } if (_Settings.BackupOxideData) { DirectoryCopy(Interface.Oxide.DataDirectory, Path.Combine(OxideBackUpRoot, "data"), true); } if (_Settings.BackupOxideLang) { DirectoryCopy(Interface.Oxide.LangDirectory, Path.Combine(OxideBackUpRoot, "lang"), true); } if (_Settings.BackupOxideLogs) { DirectoryCopy(Interface.Oxide.LogDirectory, Path.Combine(OxideBackUpRoot, "logs"), true); } if (_Settings.BackupOxidePlugins) { DirectoryCopy(Interface.Oxide.PluginDirectory, Path.Combine(OxideBackUpRoot, "plugins"), true); } foreach (string Current in _Settings.FileList) { if (!string.IsNullOrEmpty(Current)) { string CurrentPath = Path.GetFullPath(Path.Combine(Interface.Oxide.RootDirectory, Current)); if (!CurrentPath.StartsWith(Interface.Oxide.RootDirectory, StringComparison.Ordinal)) { Interface.Oxide.LogError("[DropBox] You may only access game releated directories..."); } else if ((File.GetAttributes(CurrentPath) & FileAttributes.Directory) == FileAttributes.Directory) { if (CurrentPath != Interface.Oxide.RootDirectory) { DirectoryCopy(CurrentPath, Path.Combine(FileBackUpRoot, new DirectoryInfo(CurrentPath).Name), true); } } else { File.Copy(CurrentPath, Path.Combine(FileBackUpRoot, new FileInfo(CurrentPath).Name)); } } } string FileName = string.Format("{0}.{1}.{2}.{3}.{4}.{5}.zip", DateTime.UtcNow.Year, DateTime.UtcNow.Month, DateTime.UtcNow.Day, DateTime.UtcNow.Hour, DateTime.UtcNow.Minute, DateTime.UtcNow.Second); FileStream fsOut = File.Create(Path.Combine(Interface.Oxide.RootDirectory, FileName)); ZipOutputStream zipStream = new ZipOutputStream(fsOut); zipStream.SetLevel(3); string folderName = Path.Combine(Interface.Oxide.RootDirectory, "OxideExtBackup"); int folderOffset = folderName.Length + (folderName.EndsWith("\\") ? 0 : 1); CompressFolder(folderName, zipStream, folderOffset); zipStream.IsStreamOwner = true; zipStream.Close(); Interface.Oxide.LogInfo("[DropBox] Uploading..."); Entry uploadFileEntry = dropbox.UploadFile(new FileResource(Path.Combine(Interface.Oxide.RootDirectory, FileName)), string.Format("/{0}/{1}", _Settings.BackupName, FileName), true, null); Directory.Delete(folderName, true); File.Delete(Path.Combine(Interface.Oxide.RootDirectory, FileName)); NextUpdate = NextUpdate.AddSeconds(_Settings.BackupInterval); Interface.Oxide.LogInfo("[DropBox] Uploading Complated.Next Backup : {0}", NextUpdate.ToString()); } } } } }
private void writeKMLFirstPerson(string filename) { StreamWriter stream = new StreamWriter(File.Open(filename, FileMode.Create)); System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); string header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><kml xmlns=\"http://www.opengis.net/kml/2.2\" xmlns:gx=\"http://www.google.com/kml/ext/2.2\" xmlns:kml=\"http://www.opengis.net/kml/2.2\" xmlns:atom=\"http://www.w3.org/2005/Atom\">\n <Document> <name>Paths</name> <description>Path</description>\n <Style id=\"yellowLineGreenPoly\"> <LineStyle> <color>7f00ffff</color> <width>4</width> </LineStyle> <PolyStyle> <color>7f00ff00</color> </PolyStyle> </Style>\n "; stream.Write(header); StringBuilder kml = new StringBuilder(); StringBuilder data = new StringBuilder(); double lastlat = 0; double lastlong = 0; int gpspackets = 0; int lastgpspacket = 0; foreach (Data mod in flightdata) { if (mod.model.Location.latitude == 0) { continue; } gpspackets++; if (lastlat == mod.model.Location.latitude && lastlong == mod.model.Location.longitude) { continue; } // double speed 0.05 - assumeing 10hz in log file // 1 speed = 0.1 10 / 1 = 0.1 data.Append(@" <gx:FlyTo> <gx:duration>" + ((gpspackets - lastgpspacket) * 0.1) + @"</gx:duration> <gx:flyToMode>smooth</gx:flyToMode> <Camera> <longitude>" + mod.model.Location.longitude.ToString(new System.Globalization.CultureInfo("en-US")) + @"</longitude> <latitude>" + mod.model.Location.latitude.ToString(new System.Globalization.CultureInfo("en-US")) + @"</latitude> <altitude>" + mod.model.Location.altitude.ToString(new System.Globalization.CultureInfo("en-US")) + @"</altitude> <roll>" + mod.model.Orientation.roll.ToString(new System.Globalization.CultureInfo("en-US")) + @"</roll> <tilt>" + (90 - mod.model.Orientation.tilt).ToString(new System.Globalization.CultureInfo("en-US")) + @"</tilt> <heading>" + mod.model.Orientation.heading.ToString(new System.Globalization.CultureInfo("en-US")) + @"</heading> <altitudeMode>absolute</altitudeMode> </Camera> </gx:FlyTo> "); lastlat = mod.model.Location.latitude; lastlong = mod.model.Location.longitude; lastgpspacket = gpspackets; } kml.Append(@" <Folder> <name>Flight</name> <gx:Tour> <name>Flight Do</name> <gx:Playlist> " + data + @"</gx:Playlist> </gx:Tour> </Folder> </Document> </kml> "); stream.Write(kml.ToString()); stream.Close(); // create kmz - aka zip file FileStream fs = File.Open(filename.Replace(".log.kml", ".kmz"), FileMode.Create); ZipOutputStream zipStream = new ZipOutputStream(fs); zipStream.SetLevel(9); //0-9, 9 being the highest level of compression zipStream.UseZip64 = UseZip64.Off; // older zipfile // entry 1 string entryName = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction ZipEntry newEntry = new ZipEntry(entryName); newEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(newEntry); // Zip the file in buffered chunks // the "using" will close the stream even if an exception occurs byte[] buffer = new byte[4096]; using (FileStream streamReader = File.OpenRead(filename)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); File.Delete(filename); filename = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + "block_plane_0.dae"; // entry 2 entryName = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction newEntry = new ZipEntry(entryName); newEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(newEntry); // Zip the file in buffered chunks // the "using" will close the stream even if an exception occurs buffer = new byte[4096]; using (FileStream streamReader = File.OpenRead(filename)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); zipStream.IsStreamOwner = true; // Makes the Close also Close the underlying stream zipStream.Close(); positionindex = 0; modelist.Clear(); flightdata.Clear(); position = new List <Core.Geometry.Point3D> [200]; cmd.Clear(); }
private byte[] ZipZeroLength(ISerializable data) { var formatter = new XmlFormatter(); var memStream = new MemoryStream(); using (var zipStream = new ZipOutputStream(memStream)) { zipStream.PutNextEntry(new ZipEntry("data")); formatter.Serialize(zipStream, data); zipStream.CloseEntry(); zipStream.Close(); } var result = memStream.ToArray(); memStream.Close(); return result; }
public static void ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize) { if (!File.Exists(fileToZip)) { throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!"); } using (FileStream stream = File.Create(zipedFile)) { using (ZipOutputStream stream2 = new ZipOutputStream(stream)) { using (FileStream stream3 = new FileStream(fileToZip, FileMode.Open, FileAccess.Read)) { ZipEntry entry = new ZipEntry(fileToZip.Substring(fileToZip.LastIndexOf(@"\") + 1)); stream2.PutNextEntry(entry); stream2.SetLevel(compressionLevel); byte[] buffer = new byte[blockSize]; int count = 0; try { do { count = stream3.Read(buffer, 0, buffer.Length); stream2.Write(buffer, 0, count); } while (count > 0); } catch (Exception exception) { throw exception; } stream3.Close(); } stream2.Finish(); stream2.Close(); } stream.Close(); } }
/// <summary> /// 根据fileInfoList的设置,生成新的压缩包文件 /// /// 错误处理:IEFS_Error.LastErrorMessage /// /// </summary> /// <returns></returns> public I3MsgInfo Flush() { #region 定义变量 string message; ZipOutputStream outputStream = null; int addFileCount = GetAddFileCount() + GetNormalFileCount(); long totalAddFileSize = GetTotalAddFileSize() + GetTotalNormalFileSize(); //所有需要压缩的文件的字节数 long passFileSize = 0; //已经压缩的文件的字节数 long totalPosition = 0; //总共压缩到的字节数 #endregion #region 检查临时文件与临时目录 string tmpFile = fileName + ".tmpsharpzip"; if (!I3FileUtil.CheckFileNotExists(tmpFile)) { return(new I3MsgInfo(false, "")); } string tmpDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, I3DateTimeUtil.ConvertDateTimeToLongString(DateTime.Now)); I3MsgInfo msg = I3DirectoryUtil.CheckAndClearDirctory(tmpDir); if (!msg.State) { return(msg); } #endregion try { #region 解压所有不需要替换或者删除的文件到临时目录 msg = UnCompressAllFile(tmpDir, true); if (!msg.State) { return(msg); } #endregion #region 开始压缩状态为normal、New、Change三种状态的文件到临时文件中 try { #region 压缩 outputStream = new ZipOutputStream(File.Create(tmpFile)); outputStream.SetLevel(zipLevel); if (!string.IsNullOrEmpty(passWord)) { outputStream.Password = passWord; } int fileindex = 0; foreach (I3SharpZipFileInfo info in fileInfoList) { #region 判断文件是否要参与压缩 if (info.Mode == I3SZFileInfoMode.szimDelete) { continue; } #endregion #region 发送文件个数进度信息 message = "正在压缩文件\"" + info.FileName + "\""; fileindex++; OnMutiFileProcessReport(addFileCount, fileindex, message); #endregion #region 写入ZipEntry //outputStream.PutNextEntry(GetEntry(info.FileName, info.FullName)); //自己在ZipEntry中写入CRC信息,读取时会报Eof of Header的错误 //在网上查找资料后发现,新版SharpZip.dll已经更改,不再需要自己写入CRC等信息 outputStream.PutNextEntry(new ZipEntry(info.FileName)); info.Mode = I3SZFileInfoMode.szimNormal; if (info.FileSize == 0) { continue; } #endregion FileStream sourceFileStream = null; try { #region 将文件写入压缩流 sourceFileStream = File.OpenRead(info.FullName); sourceFileStream.Position = 0; //IEFS_Stream.WriteStreamToStream(null, sourceFileStream, outputStream, blockSize, null); byte[] data = new byte[blockSize]; long longsize = 0; while (true) { int size = sourceFileStream.Read(data, 0, data.Length); if (size > 0) { outputStream.Write(data, 0, size); longsize += size; OnSingleFileProcessReport(info.FileSize, longsize, message); totalPosition = passFileSize + longsize; OnTotalBytesProcessReport(totalAddFileSize, totalPosition, message); } else { break; } } passFileSize += longsize; #endregion } finally { #region 释放单个文件的文件流 if (sourceFileStream != null) { sourceFileStream.Close(); } #endregion } } #endregion } #region 错误处理 catch (Exception ex) { return(new I3MsgInfo(false, ex.Message, ex)); } #endregion #region 释放变量 删除临时目录 finally { if (outputStream != null) { outputStream.Finish(); outputStream.Close(); } I3DirectoryUtil.DeleteDirctory(tmpDir); } #endregion #endregion #region 替换原始文件 if (!I3FileUtil.CheckFileNotExists(fileName)) { return(new I3MsgInfo(false, "")); } return(I3FileUtil.MoveFile(tmpFile, fileName, true)); #endregion } finally { I3DirectoryUtil.DeleteDirctory(tmpDir); I3FileUtil.CheckFileNotExists(tmpFile); } }
public void WriteThroughput() { outStream_ = new ZipOutputStream(new NullStream()); var startTime = DateTime.Now; long target = 0x10000000; writeTarget_ = target; outStream_.PutNextEntry(new ZipEntry("0")); WriteTargetBytes(); outStream_.Close(); var endTime = DateTime.Now; var span = endTime - startTime; Console.WriteLine("Time {0} throughput {1} KB/Sec", span, (target/1024)/span.TotalSeconds); }
public void Zip64Descriptor() { MemoryStream msw = new MemoryStreamWithoutSeek(); var outStream = new ZipOutputStream(msw); outStream.UseZip64 = UseZip64.Off; outStream.IsStreamOwner = false; outStream.PutNextEntry(new ZipEntry("StripedMarlin")); outStream.WriteByte(89); outStream.Close(); var ms = new MemoryStream(msw.ToArray()); using (var zf = new ZipFile(ms)) { Assert.IsTrue(zf.TestArchive(true)); } msw = new MemoryStreamWithoutSeek(); outStream = new ZipOutputStream(msw); outStream.UseZip64 = UseZip64.On; outStream.IsStreamOwner = false; outStream.PutNextEntry(new ZipEntry("StripedMarlin")); outStream.WriteByte(89); outStream.Close(); ms = new MemoryStream(msw.ToArray()); using (var zf = new ZipFile(ms)) { Assert.IsTrue(zf.TestArchive(true)); } }
public void EntryWithNoDataAndZip64() { MemoryStream msw = new MemoryStreamWithoutSeek(); var outStream = new ZipOutputStream(msw); outStream.IsStreamOwner = false; var ze = new ZipEntry("Striped Marlin"); ze.ForceZip64(); ze.Size = 0; outStream.PutNextEntry(ze); outStream.CloseEntry(); outStream.Finish(); outStream.Close(); var ms = new MemoryStream(msw.ToArray()); using (var zf = new ZipFile(ms)) { Assert.IsTrue(zf.TestArchive(true)); } }
public void BaseClosedAfterFailure() { var ms = new MemoryStreamEx(new byte[32]); Assert.IsFalse(ms.IsClosed, "Underlying stream should NOT be closed initially"); var blewUp = false; try { using (var stream = new ZipOutputStream(ms)) { Assert.IsTrue(stream.IsStreamOwner, "Should be stream owner by default"); try { stream.PutNextEntry(new ZipEntry("Tiny")); stream.Write(new byte[32], 0, 32); } finally { Assert.IsFalse(ms.IsClosed, "Stream should still not be closed."); stream.Close(); Assert.Fail("Exception not thrown"); } } } catch { blewUp = true; } Assert.IsTrue(blewUp, "Should have failed to write to stream"); Assert.IsTrue(ms.IsClosed, "Underlying stream should be closed"); }
protected void MakeZipFile(string name, string[] names, int size, string comment) { using (var fs = File.Create(name)) { using (var zOut = new ZipOutputStream(fs)) { zOut.SetComment(comment); for (var i = 0; i < names.Length; ++i) { zOut.PutNextEntry(new ZipEntry(names[i])); AddKnownDataToEntry(zOut, size); } zOut.Close(); } fs.Close(); } }
private int SaveVersionInfo(string sFileName) { int ret = 0; FileStream fs = null;; try { //只保存关于窗口中的信息 //fs = new FileStream(sFileName, FileMode.Create); //if(fs != null && m_LabelVersion.Text != null && m_LabelVersion.Text.Length != 0) //{ // fs.Write(System.Text.Encoding.ASCII.GetBytes(m_LabelVersion.Text), 0, m_LabelVersion.Text.Length); // ret = 1; //} //修改于2018-5-10 压缩保存相关信息 using (FileStream fsOut = File.Create(sFileName)) { using (ZipOutputStream zipStream = new ZipOutputStream(fsOut)) { bool bPowerOn = CoreInterface.GetBoardStatus() != JetStatusEnum.PowerOff; HEAD_BOARD_TYPE headBoardType = (HEAD_BOARD_TYPE)CoreInterface.get_HeadBoardType(bPowerOn); string info = m_LabelVersion.Text + "HEAD_BOARD_TYPE: " + headBoardType + "\n" + "BOARD_SYSTEM: " + (CoreInterface.IsS_system() ? "S" : "A+" + "\n" + "PRINT_HEAD_TYPE: " + Text.Replace(ResString.GetProductName(), "") + "\n"); byte[] aboutStr = Encoding.Default.GetBytes(info); ZipEntry aboutEntry = new ZipEntry("About.txt") { DateTime = DateTime.Now }; zipStream.PutNextEntry(aboutEntry); zipStream.Write(aboutStr, 0, aboutStr.Length); zipStream.CloseEntry(); string printfile = Path.Combine(Application.StartupPath, "Print.log"); Zip(printfile, zipStream); string logfile = Path.Combine(Application.StartupPath, "log.txt"); Zip(logfile, zipStream); string usersettingfile = Path.Combine(Application.StartupPath, "UserSetting.ini"); Zip(usersettingfile, zipStream); if (GlobalSetting.Instance.VendorProduct != null && GlobalSetting.Instance.VendorProduct.Length >= 8) { string folderName = Path.Combine(Application.StartupPath, GlobalSetting.Instance.VendorProduct.Substring(0, 4), GlobalSetting.Instance.VendorProduct.Substring(4, 4)); CompressFolder(folderName, zipStream); string factorywritefile = Application.StartupPath + Path.DirectorySeparatorChar + "PrinterProductList_" + GlobalSetting.Instance.VendorProduct.Substring(4, 4) + ".xml"; Zip(factorywritefile, zipStream); } zipStream.IsStreamOwner = false; zipStream.Finish(); zipStream.Close(); ret = 1; } } } catch {} finally { if (fs != null) { fs.Close(); } } return(ret); }
public static void ZipFile(string fileToZip, string zipedFile) { if (!File.Exists(fileToZip)) { throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!"); } using (FileStream stream = File.OpenRead(fileToZip)) { byte[] buffer = new byte[stream.Length]; stream.Read(buffer, 0, buffer.Length); stream.Close(); using (FileStream stream2 = File.Create(zipedFile)) { using (ZipOutputStream stream3 = new ZipOutputStream(stream2)) { ZipEntry entry = new ZipEntry(fileToZip.Substring(fileToZip.LastIndexOf(@"\") + 1)); stream3.PutNextEntry(entry); stream3.SetLevel(5); stream3.Write(buffer, 0, buffer.Length); stream3.Finish(); stream3.Close(); } } } }
public void writeKML(string filename) { try { writeGPX(filename); writeRinex(filename); } catch { } Color[] colours = { Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Blue, Color.Indigo, Color.Violet, Color.Pink }; AltitudeMode altmode = AltitudeMode.absolute; KMLRoot kml = new KMLRoot(); Folder fldr = new Folder("Log"); Style style = new Style(); style.Id = "yellowLineGreenPoly"; style.Add(new LineStyle(HexStringToColor("7f00ffff"), 4)); Style style1 = new Style(); style1.Id = "spray"; style1.Add(new LineStyle(HexStringToColor("4c0000ff"), 0)); style1.Add(new PolyStyle() { Color = HexStringToColor("4c0000ff") }); PolyStyle pstyle = new PolyStyle(); pstyle.Color = HexStringToColor("7f00ff00"); style.Add(pstyle); kml.Document.AddStyle(style); kml.Document.AddStyle(style1); int stylecode = 0xff; int g = -1; foreach (List <Point3D> poslist in position) { g++; if (poslist == null) { continue; } /* * List<PointLatLngAlt> pllalist = new List<PointLatLngAlt>(); * * foreach (var point in poslist) * { * pllalist.Add(new PointLatLngAlt(point.Y, point.X, point.Z, "")); * } * * var ans = Utilities.LineOffset.GetPolygon(pllalist, 2); * * * * while (ans.Count > 0) * { * var first = ans[0]; * var second = ans[1]; * var secondlast = ans[ans.Count - 2]; * var last = ans[ans.Count-1]; * * ans.Remove(first); * ans.Remove(last); * * var polycoords = new BoundaryIs(); * * polycoords.LinearRing = new LinearRing(); * * polycoords.LinearRing.Coordinates.Add(new Point3D(first.Lng, first.Lat, 1)); * polycoords.LinearRing.Coordinates.Add(new Point3D(second.Lng, second.Lat, 1)); * polycoords.LinearRing.Coordinates.Add(new Point3D(secondlast.Lng, secondlast.Lat, 1)); * polycoords.LinearRing.Coordinates.Add(new Point3D(last.Lng, last.Lat, 1)); * polycoords.LinearRing.Coordinates.Add(new Point3D(first.Lng, first.Lat, 1)); * * //if (!IsClockwise(polycoords.LinearRing.Coordinates)) * // polycoords.LinearRing.Coordinates.Reverse(); * * Polygon kmlpoly = new Polygon() { AltitudeMode = AltitudeMode.relativeToGround, Extrude = false, OuterBoundaryIs = polycoords }; * * Placemark pmpoly = new Placemark(); * pmpoly.Polygon = kmlpoly; * pmpoly.name = g + " test"; * pmpoly.styleUrl = "#spray"; * * fldr.Add(pmpoly); * } */ LineString ls = new LineString(); ls.AltitudeMode = altmode; ls.Extrude = true; //ls.Tessellate = true; Coordinates coords = new Coordinates(); coords.AddRange(poslist); ls.coordinates = coords; Placemark pm = new Placemark(); string mode = ""; if (g < modelist.Count) { mode = modelist[g]; } pm.name = g + " Flight Path " + mode; pm.styleUrl = "#yellowLineGreenPoly"; pm.LineString = ls; stylecode = colours[g % (colours.Length - 1)].ToArgb(); Style style2 = new Style(); Color color = Color.FromArgb(0xff, (stylecode >> 16) & 0xff, (stylecode >> 8) & 0xff, (stylecode >> 0) & 0xff); log.Info("colour " + color.ToArgb().ToString("X") + " " + color.ToKnownColor().ToString()); style2.Add(new LineStyle(color, 4)); pm.AddStyle(style2); fldr.Add(pm); } Placemark pmPOS = new Placemark(); pmPOS.name = "POS Message"; pmPOS.LineString = new LineString(); pmPOS.LineString.coordinates = new Coordinates(); Point3D lastPoint3D = new Point3D(); PointLatLngAlt lastplla = PointLatLngAlt.Zero; foreach (var item in PosLatLngAlts) { var newpoint = new Point3D(item.Lng, item.Lat, item.Alt); if (item.GetDistance(lastplla) < 0.1 && lastPoint3D.Z >= (newpoint.Z - 0.3) && lastPoint3D.Z <= (newpoint.Z + 0.3)) { continue; } pmPOS.LineString.coordinates.Add(newpoint); lastPoint3D = newpoint; lastplla = item; } pmPOS.AddStyle(style); fldr.Add(pmPOS); Folder planes = new Folder(); planes.name = "Planes"; fldr.Add(planes); Folder waypoints = new Folder(); waypoints.name = "Waypoints"; fldr.Add(waypoints); LineString lswp = new LineString(); lswp.AltitudeMode = AltitudeMode.relativeToGround; lswp.Extrude = true; Coordinates coordswp = new Coordinates(); foreach (PointLatLngAlt p1 in cmd) { if (p1.Lng == 0 && p1.Lat == 0) { continue; } coordswp.Add(new Point3D(p1.Lng, p1.Lat, p1.Alt)); } lswp.coordinates = coordswp; Placemark pmwp = new Placemark(); pmwp.name = "Waypoints"; //pm.styleUrl = "#yellowLineGreenPoly"; pmwp.LineString = lswp; if (coordswp.Count > 0) { waypoints.Add(pmwp); } int a = 0; int l = -1; Model lastmodel = null; foreach (Data mod in flightdata) { l++; if (mod.model.Location.latitude == 0) { continue; } if (lastmodel != null) { if (lastmodel.Location.Equals(mod.model.Location)) { continue; } } Placemark pmplane = new Placemark(); pmplane.name = "Plane " + a; pmplane.visibility = false; Model model = mod.model; model.AltitudeMode = altmode; model.Scale.x = 2; model.Scale.y = 2; model.Scale.z = 2; try { pmplane.description = @"<![CDATA[ <table> <tr><td>Roll: " + model.Orientation.roll + @" </td></tr> <tr><td>Pitch: " + model.Orientation.tilt + @" </td></tr> <tr><td>Yaw: " + model.Orientation.heading + @" </td></tr> <tr><td>WP dist " + mod.ntun[2] + @" </td></tr> <tr><td>tar bear " + mod.ntun[3] + @" </td></tr> <tr><td>nav bear " + mod.ntun[4] + @" </td></tr> <tr><td>alt error " + mod.ntun[5] + @" </td></tr> </table> ]]>"; } catch { } try { pmplane.Point = new KmlPoint((float)model.Location.longitude, (float)model.Location.latitude, (float)model.Location.altitude); pmplane.Point.AltitudeMode = altmode; Link link = new Link(); link.href = "block_plane_0.dae"; model.Link = link; pmplane.Model = model; planes.Add(pmplane); } catch { } // bad lat long value lastmodel = mod.model; a++; } kml.Document.Add(fldr); kml.Save(filename); // create kmz - aka zip file FileStream fs = File.Open(filename.ToLower().Replace(".log.kml", ".kmz").Replace(".bin.kml", ".kmz"), FileMode.Create); ZipOutputStream zipStream = new ZipOutputStream(fs); zipStream.SetLevel(9); //0-9, 9 being the highest level of compression zipStream.UseZip64 = UseZip64.Off; // older zipfile // entry 1 string entryName = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction ZipEntry newEntry = new ZipEntry(entryName); newEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(newEntry); // Zip the file in buffered chunks // the "using" will close the stream even if an exception occurs byte[] buffer = new byte[4096]; using (FileStream streamReader = File.OpenRead(filename)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); File.Delete(filename); filename = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + "block_plane_0.dae"; // entry 2 entryName = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction newEntry = new ZipEntry(entryName); newEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(newEntry); // Zip the file in buffered chunks // the "using" will close the stream even if an exception occurs buffer = new byte[4096]; using (FileStream streamReader = File.OpenRead(filename)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); zipStream.IsStreamOwner = true; // Makes the Close also Close the underlying stream zipStream.Close(); positionindex = 0; modelist.Clear(); flightdata.Clear(); position = new List <Core.Geometry.Point3D> [200]; cmd.Clear(); }
public static void TestZippedStream(int len, int ziplevel) { DateTime t1, t2; TimeSpan dt; Foo o = new Foo(); o.Fill(len); System.IO.FileStream zipoutfile = System.IO.File.Create(@"C:\temp\xmlteststream01.xml.zip"); ZipOutputStream ZipStream = new ZipOutputStream(zipoutfile); ZipEntry ZipEntry = new ZipEntry("Table/Table1.xml"); ZipStream.PutNextEntry(ZipEntry); ZipStream.SetLevel(ziplevel); XmlStreamSerializationInfo info = new XmlStreamSerializationInfo(); t1 = DateTime.Now; info.BeginWriting(ZipStream); info.AddValue("FooNode",o); info.EndWriting(); ZipStream.Finish(); ZipStream.Close(); zipoutfile.Close(); t2 = DateTime.Now; dt = t2-t1; Console.WriteLine("Document saved, duration {0}.",dt); t1 = DateTime.Now; ZipFile zipfile = new ZipFile(@"C:\temp\xmlteststream01.xml.zip"); System.IO.Stream zipinpstream = zipfile.GetInputStream(new ZipEntry("Table/Table1.xml")); XmlStreamDeserializationInfo info3 = new XmlStreamDeserializationInfo(); info3.BeginReading(zipinpstream); Foo o3 = (Foo)info3.GetValue(null); info3.EndReading(); zipinpstream.Close(); zipfile.Close(); t2 = DateTime.Now; dt = t2-t1; Console.WriteLine("Document restored, duration {0}.",dt); o3.EnsureEquality(len); }
public static void CreateArchive(IProgressMonitor mon, string folder, string targetFile) { string tf = Path.GetFileNameWithoutExtension(targetFile); if (tf.EndsWith(".tar")) { tf = Path.GetFileNameWithoutExtension(tf); } if (File.Exists(targetFile)) { File.Delete(targetFile); } using (Stream os = File.Create(targetFile)) { Stream outStream = os; // Create the zip file switch (GetArchiveExtension(targetFile)) { case ".tar.gz": outStream = new GZipOutputStream(outStream); goto case ".tar"; case ".tar.bz2": outStream = new BZip2OutputStream(outStream, 9); goto case ".tar"; case ".tar": TarArchive archive = TarArchive.CreateOutputTarArchive(outStream); archive.SetAsciiTranslation(false); archive.RootPath = folder; archive.ProgressMessageEvent += delegate(TarArchive ac, TarEntry e, string message) { if (message != null) { mon.Log.WriteLine(message); } }; foreach (FilePath f in GetFilesRec(new DirectoryInfo(folder))) { TarEntry entry = TarEntry.CreateEntryFromFile(f); entry.Name = f.ToRelative(folder); if (!Platform.IsWindows) { UnixFileInfo fi = new UnixFileInfo(f); entry.TarHeader.Mode = (int)fi.Protection; } else { entry.Name = entry.Name.Replace('\\', '/'); FilePermissions p = FilePermissions.S_IFREG | FilePermissions.S_IROTH | FilePermissions.S_IRGRP | FilePermissions.S_IRUSR; if (!new FileInfo(f).IsReadOnly) { p |= FilePermissions.S_IWUSR; } entry.TarHeader.Mode = (int)p; } archive.WriteEntry(entry, false); } // HACK: GNU tar expects to find a double zero record at the end of the archive. TarArchive only emits one. // This hack generates the second zero block. FieldInfo tarOutField = typeof(TarArchive).GetField("tarOut", BindingFlags.Instance | BindingFlags.NonPublic); if (tarOutField != null) { TarOutputStream tarOut = (TarOutputStream)tarOutField.GetValue(archive); tarOut.Finish(); } archive.CloseArchive(); break; case ".zip": ZipOutputStream zs = new ZipOutputStream(outStream); zs.SetLevel(5); byte[] buffer = new byte [8092]; foreach (FilePath f in GetFilesRec(new DirectoryInfo(folder))) { string name = f.ToRelative(folder); if (Platform.IsWindows) { name = name.Replace('\\', '/'); } ZipEntry infoEntry = new ZipEntry(name); zs.PutNextEntry(infoEntry); using (Stream s = File.OpenRead(f)) { int nr; while ((nr = s.Read(buffer, 0, buffer.Length)) > 0) { zs.Write(buffer, 0, nr); } } } zs.Finish(); zs.Close(); break; default: mon.Log.WriteLine("Unsupported file format: " + Path.GetFileName(targetFile)); return; } } }
public static void TestZipped() { DateTime t1, t2; TimeSpan dt; Foo o = new Foo(); o.Fill(100000); t1 = DateTime.Now; XmlDocumentSerializationInfo info = new XmlDocumentSerializationInfo(); info.AddValue("FooNode",o); System.IO.FileStream zipoutfile = System.IO.File.Create(@"C:\temp\xmltest03.xml.zip"); ZipOutputStream ZipStream = new ZipOutputStream(zipoutfile); ZipEntry ZipEntry = new ZipEntry("Table/Table1.xml"); ZipStream.PutNextEntry(ZipEntry); ZipStream.SetLevel(7); info.Doc.Save(ZipStream); ZipStream.Finish(); ZipStream.Close(); zipoutfile.Close(); t2 = DateTime.Now; dt = t2-t1; Console.WriteLine("Document saved, duration {0}.",dt); t1 = DateTime.Now; ZipFile zipfile = new ZipFile(@"C:\temp\xmltest03.xml.zip"); System.IO.Stream zipinpstream = zipfile.GetInputStream(new ZipEntry("Table/Table1.xml")); XmlDocument doc3 = new XmlDocument(); doc3.Load(zipinpstream); XmlDocumentSerializationInfo info3 = new XmlDocumentSerializationInfo(doc3); Foo o3 = (Foo)info3.GetValue(null); zipinpstream.Close(); zipfile.Close(); t2 = DateTime.Now; dt = t2-t1; Console.WriteLine("Document restored, duration {0}.",dt); }
protected void MakeZipFile(Stream storage, bool isOwner, string[] names, int size, string comment) { using (var zOut = new ZipOutputStream(storage)) { zOut.IsStreamOwner = isOwner; zOut.SetComment(comment); for (var i = 0; i < names.Length; ++i) { zOut.PutNextEntry(new ZipEntry(names[i])); AddKnownDataToEntry(zOut, size); } zOut.Close(); } }
public 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); }
/// <summary> /// 压缩文件 /// </summary> /// <param name="filePath">文件地址</param> /// <param name="zipPath">生成 Zip 路径</param> /// <param name="password">密码</param> /// <param name="compressLevel">压缩等级,取值范围:0-9</param> /// <returns></returns> public static bool Compress(string filePath, string zipPath, string password = "", int compressLevel = 6) { if (!File.Exists(filePath)) { throw new Exception(FileNotExistsException); } ZipOutputStream zipStream = null; FileStream fileStream = null; ZipEntry zipEntry = null; try { // 检查后缀 string suffix = FileHelper.GetSuffix(zipPath); // 如果生成文件后缀不是 .zip|.rar,抛出异常 if (ZipFormat.FormatList.IndexOf(suffix) < 0) { throw new Exception(ZipFormatErrorException); } // 创建文件目录 bool directoryResult = FileHelper.CreateDirectory(zipPath); if (!directoryResult) { return(false); } fileStream = File.OpenRead(filePath); byte[] buffer = new byte[fileStream.Length]; fileStream.Read(buffer, 0, buffer.Length); fileStream.Close(); using (fileStream = File.Create(zipPath)) { using (zipStream = new ZipOutputStream(fileStream)) { if (!string.IsNullOrEmpty(password)) { zipStream.Password = password; } zipEntry = new ZipEntry(Path.GetFileName(filePath)); zipStream.PutNextEntry(zipEntry); zipStream.SetLevel(compressLevel); zipStream.Write(buffer, 0, buffer.Length); } } return(true); } catch { throw; } finally { if (zipStream != null) { zipStream.Close(); } if (fileStream != null) { fileStream.Close(); } if (zipEntry != null) { zipEntry = null; } } }
public static void Zip(string FilePath, string ZipFileName, string Password) { //目标zip文件是否已经存在 //File.Delete(ZipFileName); // This setting will strip the leading part of the folder path in the entries, to // make the entries relative to the starting folder. // To include the full path for each entry up to the drive root, assign folderOffset = 0. int folderOffset = 0; string[] files; //路径是文件还是目录呢? if (File.Exists(FilePath)) { files = new string[] { FilePath }; folderOffset = FilePath.LastIndexOf("\\"); } else { files = Directory.GetFiles(FilePath, "*.*", SearchOption.AllDirectories); folderOffset = FilePath.Length + (FilePath.EndsWith("\\") ? 0 : 1); } FileStream fsOut = File.Create(ZipFileName); ZipOutputStream zipStream = new ZipOutputStream(fsOut); zipStream.SetLevel(9); //0-9, 9 being the highest level of compression zipStream.Password = Password; // optional. Null is the same as not setting. Required if using AES. foreach (string filename in files) { //如果目录的文件和目标zip文件重名,跳过 if (new FileInfo(filename).FullName == new FileInfo(ZipFileName).FullName) { continue; } FileInfo fi = new FileInfo(filename); string entryName = filename.Substring(folderOffset); // Makes the name in zip based on the folder entryName = ZipEntry.CleanName(entryName); // Removes drive from name and fixes slash direction ZipEntry newEntry = new ZipEntry(entryName); newEntry.DateTime = fi.LastWriteTime; // Note the zip format stores 2 second granularity // Specifying the AESKeySize triggers AES encryption. Allowable values are 0 (off), 128 or 256. // A password on the ZipOutputStream is required if using AES. newEntry.AESKeySize = 256; // To permit the zip to be unpacked by built-in extractor in WinXP and Server2003, WinZip 8, Java, and other older code, // you need to do one of the following: Specify UseZip64.Off, or set the Size. // If the file may be bigger than 4GB, or you do not need WinXP built-in compatibility, you do not need either, // but the zip will be in Zip64 format which not all utilities can understand. zipStream.UseZip64 = UseZip64.Off; newEntry.Size = fi.Length; zipStream.PutNextEntry(newEntry); // Zip the file in buffered chunks // the "using" will close the stream even if an exception occurs byte[] buffer = new byte[4096]; using (FileStream streamReader = File.OpenRead(filename)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); } zipStream.IsStreamOwner = true; // Makes the Close also Close the underlying stream zipStream.Close(); }
static void Main(string[] args) { //get the setting values GetSettingValues(); //check if the backup directory is exists if (!Directory.Exists(_BackupDirectory)) { try { Directory.CreateDirectory(_BackupDirectory); WriteLine(">>> Backup folder is not exists. The folder has been created successfully."); _MessageList.Add(">>> Backup folder is not exists. The folder has been created successfully."); } catch (Exception ex) { WriteLine("Error: " + ex.Message); _MessageList.Add("Error Creating Backup Folder: " + ex.Message); } } else { //Create today date backup folder if (!Directory.Exists(_BackupDirectory + "/" + DateTime.Now.ToString("dd MMM yyyy"))) { try { Directory.CreateDirectory(_BackupDirectory + "/" + DateTime.Now.ToString("dd MMM yyyy")); WriteLine(">>> Backup folder (" + DateTime.Now.ToString("dd MMM yyyy") + ") is not exists. The folder has been created successfully."); _MessageList.Add(">>> Backup folder (" + DateTime.Now.ToString("dd MMM yyyy") + ") is not exists. The folder has been created successfully."); } catch (Exception ex) { WriteLine("Error: " + ex.Message); _MessageList.Add("Error Creating Backup Folder (" + DateTime.Now.ToString("dd MMM yyyy") + ") : " + ex.Message); } } else { //backup the source directories foreach (string sourceDir in _SourceDirectories) { DirectoryInfo dir = new DirectoryInfo(sourceDir); _MessageList.Add("Creating Folder Zip => " + dir.Name); WriteLine("Creating Folder Zip => " + dir.Name); ZipOutputStream zip = new ZipOutputStream(File.Create(_BackupDirectory + "/" + DateTime.Now.ToString("dd MMM yyyy") + "/" + dir.Name + ".zip")); zip.SetLevel(9); ZipFolder(sourceDir, sourceDir, zip); zip.Finish(); zip.Close(); } //backup database foreach (string dbName in _SQLDatabaseNames) { try { WriteLine("BACKUP DATABASE [" + dbName + "] TO DISK = " + @"'" + _BackupDirectory + "/" + DateTime.Now.ToString("dd MMM yyyy") + "/" + dbName + ".bak'" + " WITH FORMAT, MEDIANAME = '" + dbName + "', NAME = '" + dbName + "';"); _MessageList.Add("BACKUP DATABASE [" + dbName + "] TO DISK = " + @"'" + _BackupDirectory + "/" + DateTime.Now.ToString("dd MMM yyyy") + "/" + dbName + ".bak'" + " WITH FORMAT, MEDIANAME = '" + dbName + "', NAME = '" + dbName + "';"); RunQuery(dbName, "BACKUP DATABASE [" + dbName + "] TO DISK = " + @"'" + _BackupDirectory + "/" + DateTime.Now.ToString("dd MMM yyyy") + "/" + dbName + ".bak'" + " WITH FORMAT, MEDIANAME = '" + dbName + "', NAME = '" + dbName + "';"); WriteLine(@">>> Backup file for " + dbName + " has been succesfully created"); _MessageList.Add(@">>> Backup database file for " + dbName + " has been succesfully created"); ZipOutputStream zipDB = new ZipOutputStream(File.Create(_BackupDirectory + "/" + DateTime.Now.ToString("dd MMM yyyy") + "/DATABASE_" + dbName + ".zip")); _MessageList.Add("Creating Database Zip => " + dbName); zipDB.SetLevel(9); string relativePath = (_BackupDirectory + "/" + DateTime.Now.ToString("dd MMM yyyy")).Substring((_BackupDirectory + "/" + DateTime.Now.ToString("dd MMM yyyy")).Length) + "/"; AddFileToZip(zipDB, relativePath, _BackupDirectory + "/" + DateTime.Now.ToString("dd MMM yyyy") + "/" + dbName + ".bak"); zipDB.Finish(); zipDB.Close(); } catch (Exception ex) { WriteLine("Error backing up database (" + dbName + ") : " + ex.Message.ToString()); _MessageList.Add("Error backing up databasee (" + dbName + ") :" + ex.Message); } } //Delete the bak file foreach (string dbName in _SQLDatabaseNames) { try { File.Delete(_BackupDirectory + "/" + DateTime.Now.ToString("dd MMM yyyy") + "/" + dbName + ".bak"); } catch (Exception ex) { WriteLine("Error deleting database (" + dbName + ").bak file : " + ex.Message.ToString()); _MessageList.Add("Error deleting database (" + dbName + ").bak file : " + ex.Message.ToString()); } } //check if need to delete backup folder if (_BackupDays != string.Empty) { int days = 0; int.TryParse(_BackupDays, out days); if (days > 0) { DirectoryInfo curDir = new DirectoryInfo(_BackupDirectory); DirectoryInfo[] dirList = curDir.GetDirectories(); foreach (DirectoryInfo objDir in dirList) { if ((DateTime.Now - Convert.ToDateTime(objDir.Name)).TotalDays > days) { DeleteDirectory(objDir); } } } } } } }
public static int Zip(string destFolder, string[] srcFiles, string folderName, string password, CompressLevel level) { ZipOutputStream zipStream = null; FileStream streamWriter = null; int count = 0; try { //Use Crc32 Crc32 crc32 = new Crc32(); //Create Zip File zipStream = new ZipOutputStream(File.Create(destFolder)); //Specify Level zipStream.SetLevel(Convert.ToInt32(level)); //Specify Password if (password != null && password.Trim().Length > 0) { zipStream.Password = password; } //Foreach File foreach (string file in srcFiles) { //Check Whether the file exists if (!File.Exists(file)) { throw new FileNotFoundException(file); } //Read the file to stream streamWriter = File.OpenRead(file); byte[] buffer = new byte[streamWriter.Length]; streamWriter.Read(buffer, 0, buffer.Length); streamWriter.Close(); //Specify ZipEntry crc32.Reset(); crc32.Update(buffer); ZipEntry zipEntry = new ZipEntry(Path.Combine(folderName, Path.GetFileName(file))); zipEntry.DateTime = DateTime.Now; zipEntry.Size = buffer.Length; zipEntry.Crc = crc32.Value; //Put file info into zip stream zipStream.PutNextEntry(zipEntry); //Put file data into zip stream zipStream.Write(buffer, 0, buffer.Length); count++; } } catch { throw; } finally { //Clear Resource if (streamWriter != null) { streamWriter.Close(); } if (zipStream != null) { zipStream.Finish(); zipStream.Close(); } } return(count); }
private static Boolean enviar_facturacion_electronica(string xml1, string xml2, string _doc) { Boolean valor = false; try { string ruta_zip = Path.GetDirectoryName(Application.ExecutablePath).ToString() + "/archivo.zip"; if (File.Exists(ruta_zip)) { File.Delete(ruta_zip); } //crear archivo zip ZipOutputStream zipOut = new ZipOutputStream(File.Create(@ruta_zip)); //********************* String[] filenames = { xml1, xml2 }; for (Int32 i = 0; i < filenames.Length; ++i) { string _archivo_xml = filenames[i].ToString(); FileInfo fi = new FileInfo(_archivo_xml); ICSharpCode.SharpZipLib.Zip.ZipEntry entry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fi.Name); FileStream sReader = File.OpenRead(_archivo_xml); byte[] buff = new byte[Convert.ToInt32(sReader.Length)]; sReader.Read(buff, 0, (int)sReader.Length); entry.DateTime = fi.LastWriteTime; entry.Size = sReader.Length; sReader.Close(); zipOut.PutNextEntry(entry); zipOut.Write(buff, 0, buff.Length); } zipOut.Finish(); zipOut.Close(); byte[] file = File.ReadAllBytes(ruta_zip); valor = true; //si el archivo existe entonces lo eliminamos porque ya se transformo en bytes if (File.Exists(ruta_zip)) { File.Delete(ruta_zip); } //EfactService.BataTransactionServiceClient _client = new EfactService.BataTransactionServiceClient(); //EfactService.transactionResponse[] _valida = null; //switch (_doc) //{ // case "B": // _valida = _client.sendBoleta(file); // break; // case "F": // _valida = _client.sendInvoice(file); // break; // case "NC": // _valida = _client.sendCreditNote(file); // break; //} //if (_doc == "B") //{ // _valida = _client.sendBoleta(file); //} //else //{ // _valida = _client.sendInvoice(file); //} //valor del web serice 0 llego correctamente efact //string _codigo_valida = _valida[0].responseCode.ToString(); //if (_codigo_valida == "0") //{ // valor = true; //} //else //{ // valor = false; //} return(valor); } catch (Exception exc) { valor = false; } return(valor); }
public static void writeKML(string filename, Dictionary <int, List <CurrentState> > flightdatas, Action <double> progressBar1, double basealt = 0) { SharpKml.Dom.AltitudeMode altmode = SharpKml.Dom.AltitudeMode.Absolute; Color[] colours = { Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Blue, Color.Indigo, Color.Violet, Color.Pink }; Document kml = new Document(); AddNamespace(kml, "gx", "http://www.google.com/kml/ext/2.2"); Style style = new Style(); style.Id = "yellowLineGreenPoly"; style.Line = new LineStyle(new Color32(HexStringToColor("7f00ffff")), 4); PolygonStyle pstyle = new PolygonStyle(); pstyle.Color = new Color32(HexStringToColor("7f00ff00")); style.Polygon = pstyle; kml.AddStyle(style); Style stylet = new Style(); stylet.Id = "track"; SharpKml.Dom.IconStyle ico = new SharpKml.Dom.IconStyle(); LabelStyle lst = new LabelStyle(); lst.Scale = 0; stylet.Icon = ico; ico.Icon = new IconStyle.IconLink( new Uri("http://earth.google.com/images/kml-icons/track-directional/track-none.png")); stylet.Icon.Scale = 0.5; stylet.Label = lst; kml.AddStyle(stylet); foreach (var flightdatai in flightdatas) { var sysid = flightdatai.Key; var flightdata = flightdatai.Value; Tour tour = new Tour() { Name = "First Person View" }; Playlist tourplaylist = new Playlist(); // create sub folders Folder planes = new Folder(); planes.Name = "Models " + sysid; kml.AddFeature(planes); Folder points = new Folder(); points.Name = "Points " + sysid; kml.AddFeature(points); // coords for line string CoordinateCollection coords = new CoordinateCollection(); int a = 1; int c = -1; DateTime lasttime = DateTime.MaxValue; DateTime starttime = DateTime.MinValue; Color stylecolor = Color.AliceBlue; string mode = ""; if (flightdata.Count > 0) { mode = flightdata[0].mode; } foreach (CurrentState cs in flightdata) { progressBar1(50 + (int)((float)a / (float)flightdata.Count * 100.0f / 2.0f)); if (starttime == DateTime.MinValue) { starttime = cs.datetime; lasttime = cs.datetime; } if (mode != cs.mode || flightdata.Count == a) { c++; LineString ls = new LineString(); ls.AltitudeMode = altmode; ls.Extrude = true; ls.Coordinates = coords; Placemark pm = new Placemark(); pm.Name = c + " Flight Path " + mode; pm.StyleUrl = new Uri("#yellowLineGreenPoly", UriKind.Relative); pm.Geometry = ls; SharpKml.Dom.TimeSpan ts = new SharpKml.Dom.TimeSpan(); ts.Begin = starttime; ts.End = cs.datetime; pm.Time = ts; // setup for next line mode = cs.mode; starttime = cs.datetime; stylecolor = colours[c % (colours.Length - 1)]; Style style2 = new Style(); style2.Line = new LineStyle(new Color32(stylecolor), 4); pm.StyleSelector = style2; kml.AddFeature(pm); coords = new CoordinateCollection(); } Vector location = new Vector(cs.lat, cs.lng, cs.altasl); if (basealt != 0) { location.Altitude = cs.alt + basealt; coords.Add(location); } else { coords.Add(location); } SharpKml.Dom.Timestamp tstamp = new SharpKml.Dom.Timestamp(); tstamp.When = cs.datetime; FlyTo flyto = new FlyTo(); flyto.Duration = (cs.datetime - lasttime).TotalMilliseconds / 1000.0; flyto.Mode = FlyToMode.Smooth; SharpKml.Dom.Camera cam = new SharpKml.Dom.Camera(); cam.AltitudeMode = altmode; cam.Latitude = cs.lat; cam.Longitude = cs.lng; cam.Altitude = location.Altitude; cam.Heading = cs.yaw; cam.Roll = -cs.roll; cam.Tilt = (90 - (cs.pitch * -1)); cam.GXTimePrimitive = tstamp; flyto.View = cam; //if (Math.Abs(flyto.Duration.Value) > 0.1) { tourplaylist.AddTourPrimitive(flyto); lasttime = cs.datetime; } Placemark pmplane = new Placemark(); pmplane.Name = "Point " + a; pmplane.Time = tstamp; pmplane.Visibility = false; SharpKml.Dom.Location loc = new SharpKml.Dom.Location(); loc.Latitude = cs.lat; loc.Longitude = cs.lng; loc.Altitude = location.Altitude; if (loc.Altitude < 0) { loc.Altitude = 0.01; } SharpKml.Dom.Orientation ori = new SharpKml.Dom.Orientation(); ori.Heading = cs.yaw; ori.Roll = -cs.roll; ori.Tilt = -cs.pitch; SharpKml.Dom.Scale sca = new SharpKml.Dom.Scale(); sca.X = 2; sca.Y = 2; sca.Z = 2; Model model = new Model(); model.Location = loc; model.Orientation = ori; model.AltitudeMode = altmode; model.Scale = sca; try { Description desc = new Description(); desc.Text = @"<![CDATA[ <table> <tr><td>Roll: " + model.Orientation.Roll.Value.ToString("0.00") + @" </td></tr> <tr><td>Pitch: " + model.Orientation.Tilt.Value.ToString("0.00") + @" </td></tr> <tr><td>Yaw: " + model.Orientation.Heading.Value.ToString("0.00") + @" </td></tr> <tr><td>Time: " + cs.datetime.ToString("HH:mm:sszzzzzz") + @" </td></tr> </table> ]]>"; // ]]>"; pmplane.Description = desc; } catch { } SharpKml.Dom.Link link = new SharpKml.Dom.Link(); link.Href = new Uri("block_plane_0.dae", UriKind.Relative); model.Link = link; pmplane.Geometry = model; planes.AddFeature(pmplane); /// Placemark pmt = new Placemark(); SharpKml.Dom.Point pnt = new SharpKml.Dom.Point(); pnt.AltitudeMode = altmode; pnt.Coordinate = location; pmt.Name = "" + a; pmt.Description = pmplane.Description; pmt.Time = tstamp; pmt.Geometry = pnt; pmt.StyleUrl = new Uri("#track", UriKind.Relative); points.AddFeature(pmt); a++; } tour.Playlist = tourplaylist; kml.AddFeature(tour); } Serializer serializer = new Serializer(); serializer.Serialize(kml); //Console.WriteLine(serializer.Xml); StreamWriter sw = new StreamWriter(filename); sw.Write(serializer.Xml); sw.Close(); // create kmz - aka zip file FileStream fs = File.Open(filename.Replace(Path.GetExtension(filename), ".kmz"), FileMode.Create); ZipOutputStream zipStream = new ZipOutputStream(fs); zipStream.SetLevel(9); //0-9, 9 being the highest level of compression zipStream.UseZip64 = UseZip64.Off; // older zipfile // entry 1 string entryName = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction ZipEntry newEntry = new ZipEntry(entryName); newEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(newEntry); // Zip the file in buffered chunks // the "using" will close the stream even if an exception occurs byte[] buffer = new byte[4096]; using (FileStream streamReader = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); File.Delete(filename); filename = Settings.GetRunningDirectory() + "block_plane_0.dae"; // entry 2 entryName = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction newEntry = new ZipEntry(entryName); newEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(newEntry); // Zip the file in buffered chunks // the "using" will close the stream even if an exception occurs buffer = new byte[4096]; using (FileStream streamReader = File.OpenRead(filename)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); zipStream.IsStreamOwner = true; // Makes the Close also Close the underlying stream zipStream.Close(); }
public void SaveXML() { ZipOutputStream zipStream = null; try { // Выходной поток FileStream fsOut = File.Create(Path); zipStream = new ZipOutputStream(fsOut); ZipEntry newEntry = new ZipEntry(DefaultMetaFileName); zipStream.PutNextEntry(newEntry); // Файлы, сразу их писатьне получится, так что сначала будем запоминать, что надо бы записать // Непосредственная апись в конце LinkedList <FileEntry> fileEntries = new LinkedList <FileEntry>(); XmlWriterSettings settings = new XmlWriterSettings(); settings.CloseOutput = false; // Не закрывать ZIP поток после записи метафайла! settings.Indent = true; using (var w = XmlTextWriter.Create(zipStream, settings)) { w.WriteStartElement("File"); w.WriteStartElement("Versions"); // Сами файлы будут иметь имя просто 0, 1, 2, ... int counter = 0; foreach (Version version in _codeFile._versions) { w.WriteStartElement("Version"); w.WriteAttributeString("Key", version.Key.ToString()); w.WriteAttributeString("Mark", version.Mark); w.WriteStartElement("Text"); w.WriteAttributeString("Hash", version.Document.Text.GetHashCode().ToString()); string name = (counter++).ToString(); w.WriteAttributeString("Name", name); w.WriteEndElement(); // Text fileEntries.AddLast(new FileEntry { Bytes = _UTF8Encoder.GetBytes(version.Document.Text), Name = name }); w.WriteStartElement("Checkboxes"); foreach (TextAnchor cb in version.Checkboxes.Where(cb => !cb.IsDeleted)) { w.WriteStartElement("Checkbox"); w.WriteAttributeString("Offset", cb.Offset.ToString()); w.WriteEndElement(); // Checkbox } w.WriteEndElement(); // Checkboxes w.WriteStartElement("Comments"); foreach (Comment comment in version.Comments.Where(comment => !comment.Anchor.IsDeleted)) { w.WriteStartElement("Comment"); w.WriteAttributeString("Offset", comment.Anchor.Offset.ToString()); w.WriteAttributeString("Text", comment.Text); w.WriteEndElement(); // Comment } w.WriteEndElement(); // Comments w.WriteStartElement("ColorSegments"); foreach (ColorSegment segment in version.ColorSegments.Where(segment => segment.IsAcive())) { w.WriteStartElement("ColorSegment"); w.WriteAttributeString("Start", segment.Start.Offset.ToString()); w.WriteAttributeString("End", segment.End.Offset.ToString()); w.WriteAttributeString("Color", segment.Color.Color.ToString()); w.WriteEndElement(); // ColorSegment } w.WriteEndElement(); // ColorSegments w.WriteStartElement("Bookmarks"); foreach (Bookmark bookmark in version.Bookmarks.Where(bookmark => bookmark.IsActive)) { w.WriteStartElement("Bookmark"); w.WriteAttributeString("Offset", bookmark.Offset.ToString()); w.WriteAttributeString("Key", bookmark.Key.ToString()); w.WriteAttributeString("Mark", bookmark.Mark); w.WriteEndElement(); // Bookmark } w.WriteEndElement(); // Bookmarks w.WriteEndElement(); // Version } w.WriteEndElement(); // Versions w.WriteEndElement(); // File } zipStream.CloseEntry(); // Закончили метафайл // Записываем сами файлы foreach (FileEntry entry in fileEntries) { ZipEntry zipEntry = new ZipEntry(entry.Name); zipStream.PutNextEntry(zipEntry); zipStream.Write(entry.Bytes, 0, entry.Bytes.Length); zipStream.CloseEntry(); } } catch (IOException ex) { throw new SaveCodeFileException(Path, ex); } catch (UnauthorizedAccessException ex) { throw new SaveCodeFileException(Path, ex); } finally { if (zipStream != null) { zipStream.IsStreamOwner = true; zipStream.Close(); // Закончили весь ZIP архив } } }
private void ZipSelectedAssetsAndSend() { int?currentOrderId = CurrentOrder.OrderId; m_Logger.DebugFormat("User: {0} has selected assets to zip from order: {1}", CurrentUser.FullName, currentOrderId); // The folder where the zip file should be stored string sessionFolder = SessionHelper.GetForCurrentSession().CreateSessionTempFolder(); // Unique filename strings string dateString = DateTime.Now.ToString("yyyyMMddHHmmss"); string guid = GeneralUtils.GetGuid(); // The actual filename of the zip file on disk string outputFilename = string.Format("assets_from_order_{0}_{1}_{2}.zip", currentOrderId, dateString, guid); // The full path to the zip file on disk string outputPath = Path.Combine(sessionFolder, outputFilename); m_Logger.DebugFormat("Zip file will be stored in: {0}", outputPath); using (ZipOutputStream zos = new ZipOutputStream(File.Create(outputPath))) { try { zos.SetLevel(9); zos.SetComment(string.Format("Selected assets from order {0} on {1}", CurrentOrder.OrderId, CurrentOrder.OrderDate.ToString(Global.DateFormat))); foreach (OrderItem orderItem in CurrentOrder.OrderItemList) { if (Response.IsClientConnected && ShouldDownload(orderItem)) { // Get the asset Asset asset = orderItem.Asset; // Get the path to the asset file AssetFileInfo info = new AssetFileInfo(asset); // Get actual path string path = info.FilePath; // Check if a different image format is being requested if (AssetTypeChecker.IsImage(asset.FileExtension)) { SelectedOrderItem soi = SelectedOrderItems.Get(orderItem.OrderItemId.GetValueOrDefault()); path = AssetImageManager.GetResizedAssetImage(asset, soi.AssetImageSizeId, soi.DownloadFormat, true); } // Filename string filename = string.Concat(Path.GetFileNameWithoutExtension(asset.Filename), "_", asset.FileReference, (Path.GetExtension(path) ?? ".unknown").ToLower()); // Add the file to the generated zip AddFileToZipOutputStream(filename, path, zos); // Log this download for reporting AuditLogManager.LogAssetAction(asset, CurrentUser, AuditAssetAction.DownloadedAssetFile); AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.DownloadAsset, string.Format("Downloaded AssetId: {0} as part of zipped download for OrderId: {1}", asset.AssetId, CurrentOrder.OrderId)); } } } finally { zos.Finish(); zos.Close(); } } string downloadUrl = string.Format("~/GetZipDownload.ashx?OrderId={0}&d={1}&guid={2}", currentOrderId, dateString, guid); Response.Redirect(downloadUrl); }
void BuildPackageInternal(IProgressStatus monitor, string targetDirectory, string filePath) { AddinDescription conf = registry.GetAddinDescription(monitor, filePath); if (conf == null) { monitor.ReportError("Could not read add-in file: " + filePath, null); return; } string basePath = Path.GetDirectoryName(filePath); if (targetDirectory == null) { targetDirectory = basePath; } // Generate the file name string name; if (conf.LocalId.Length == 0) { name = Path.GetFileNameWithoutExtension(filePath); } else { name = conf.LocalId; } name = Addin.GetFullId(conf.Namespace, name, conf.Version); name = name.Replace(',', '_').Replace(".__", "."); string outFilePath = Path.Combine(targetDirectory, name) + ".mpack"; ZipOutputStream s = new ZipOutputStream(File.Create(outFilePath)); s.SetLevel(5); // Generate a stripped down description of the add-in in a file, since the complete // description may be declared as assembly attributes XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = false; doc.LoadXml(conf.SaveToXml().OuterXml); CleanDescription(doc.DocumentElement); MemoryStream ms = new MemoryStream(); XmlTextWriter tw = new XmlTextWriter(ms, System.Text.Encoding.UTF8); tw.Formatting = Formatting.Indented; doc.WriteTo(tw); tw.Flush(); byte[] data = ms.ToArray(); ZipEntry infoEntry = new ZipEntry("addin.info"); s.PutNextEntry(infoEntry); s.Write(data, 0, data.Length); // Now add the add-in files ArrayList list = new ArrayList(); if (!conf.AllFiles.Contains(Path.GetFileName(filePath))) { list.Add(Path.GetFileName(filePath)); } foreach (string f in conf.AllFiles) { list.Add(f); } monitor.Log("Creating package " + Path.GetFileName(outFilePath)); foreach (string file in list) { string fp = Path.Combine(basePath, file); using (FileStream fs = File.OpenRead(fp)) { byte[] buffer = new byte [fs.Length]; fs.Read(buffer, 0, buffer.Length); ZipEntry entry = new ZipEntry(file); s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); } } s.Finish(); s.Close(); }
public static void GerarArquivoCompactado(string nomeArquivos, string diretorioSaida, string arquivoSaidaZip, List <Models.SqlServer.Enriquecimento.SufixoArquivosCompactados> listSufixoArquivosCompactados) { string partialName = nomeArquivos; DirectoryInfo hdDirectoryInWhichToSearch = null; FileInfo[] filesInDir = null; List <string> listDiretorioEArquivo = new List <string>(); hdDirectoryInWhichToSearch = new DirectoryInfo(diretorioSaida); filesInDir = hdDirectoryInWhichToSearch.GetFiles("*" + partialName + "*.*"); foreach (FileInfo foundFile in filesInDir) { if ((foundFile.Directory != null) && (string.IsNullOrEmpty(foundFile.Directory.FullName) == false) && (string.IsNullOrEmpty(foundFile.Name) == false) && (listSufixoArquivosCompactados != null) && (listSufixoArquivosCompactados.Count > 0)) { var resultCount = (from t1 in listSufixoArquivosCompactados where foundFile.Name.ToUpper().Contains(t1.SufixoArquivo.ToUpper()) == true select t1).Count(); if (resultCount > 0) { listDiretorioEArquivo.Add(foundFile.Directory.FullName + "\\" + foundFile.Name); } } } if ((listDiretorioEArquivo != null) && (listDiretorioEArquivo.Count > 0)) { using (ZipOutputStream strmZipOutputStream = new ZipOutputStream(File.Create(diretorioSaida + arquivoSaidaZip))) { foreach (var item in listDiretorioEArquivo) { FileInfo fi = new FileInfo(item); ZipEntry entry = new ZipEntry(fi.Name); strmZipOutputStream.PutNextEntry(entry); FileStream fs = File.OpenRead(fi.FullName); try { int bytesRead = 0; var transferBuffer = new byte[1024]; do { bytesRead = fs.Read(transferBuffer, 0, transferBuffer.Length); strmZipOutputStream.Write(transferBuffer, 0, bytesRead); }while (bytesRead > 0); } catch { } finally { fs.Close(); } } strmZipOutputStream.CloseEntry(); strmZipOutputStream.Finish(); strmZipOutputStream.Close(); } } }
/// <summary> /// Main method /// </summary> /// <param name="stZipPath">path of the archive wanted</param> /// <param name="stDirToZip">path of the directory we want to create, without ending backslash</param> public static void CreateZip(string stZipPath, string stDirToZip) { try { //Sanitize inputs stDirToZip = Path.GetFullPath(stDirToZip); stZipPath = Path.GetFullPath(stZipPath); TextLogger2.Log("Zip directory " + stDirToZip); //Recursively parse the directory to zip Stack<FileInfo> stackFiles = DirExplore(stDirToZip); ZipOutputStream zipOutput = null; if (File.Exists(stZipPath)) File.Delete(stZipPath); Crc32 crc = new Crc32(); zipOutput = new ZipOutputStream(File.Create(stZipPath)); zipOutput.SetLevel(6); // 0 - store only to 9 - means best compression TextLogger2.Log(stackFiles.Count + " files to zip.\n"); int index = 0; foreach (FileInfo fi in stackFiles) { ++index; //int percent = (int)((float)index / ((float)stackFiles.Count / 100)); //if (percent % 1 == 0) //{ // Console.CursorLeft = 0; // Console.Write(_stSchon[index % _stSchon.Length].ToString() + " " + percent + "% done."); //} FileStream fs = File.OpenRead(fi.FullName); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); //Create the right arborescence within the archive string stFileName = fi.FullName.Remove(0, stDirToZip.Length + 1); ZipEntry entry = new ZipEntry(stFileName); entry.DateTime = DateTime.Now; // set Size and the crc, because the information // about the size and crc should be stored in the header // if it is not set it is automatically written in the footer. // (in this case size == crc == -1 in the header) // Some ZIP programs have problems with zip files that don't store // the size and crc in the header. entry.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; zipOutput.PutNextEntry(entry); zipOutput.Write(buffer, 0, buffer.Length); } zipOutput.Finish(); zipOutput.Close(); zipOutput = null; } catch (Exception) { throw; } }
private Stream Encode(Stream inStream) { Stream outStream = inStream; string inFile = Path.GetTempFileName(); string outFile = Path.ChangeExtension(inFile, "zip"); try { ZipOutputStream zipStream = new ZipOutputStream( File.Create(outFile) ); // get password, if supplied if ((_password != null) && (_password != "")) { zipStream.Password = _password; } // get compression level, if supplied int compressionlevel = DEFAULT_COMPRESSIONLEVEL; if ((_compressionlevel != null) && (_compressionlevel != "")) { compressionlevel = Convert.ToInt32(_compressionlevel); } if ((compressionlevel < 0) || (compressionlevel > 9)) { compressionlevel = DEFAULT_COMPRESSIONLEVEL; } zipStream.SetLevel(compressionlevel); // get message filename, if supplied string filename = (((_filename != null) && (_filename != "")) ? _filename : DEFAULT_FILENAME); ZipEntry entry = new ZipEntry(filename); zipStream.PutNextEntry(entry); // copy the input into the compressed output stream byte[] buffer = new byte[4096]; int count = 0; while ((count = inStream.Read(buffer, 0, buffer.Length)) != 0) { zipStream.Write(buffer, 0, count); } zipStream.Finish(); zipStream.Close(); outStream = Probiztalk.Samples.PipelineUtilities. FileStreamReadWrite.ReadFileToMemoryStream(outFile); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex); } finally { if (File.Exists(inFile)) { File.Delete(inFile); } if (File.Exists(outFile)) { File.Delete(outFile); } } return(outStream); }
/// <summary>功能:zip格式压缩文件 /// </summary> /// <param name="dirPath">被压缩的文件夹夹路径</param> /// <param name="zipFilePath">生成压缩文件的路径,为空则默认与被压缩文件夹同一级目录,名称为:文件夹名+.zip</param> /// <param name="fileName">传出正在处理的文件名。</param> /// <param name="fileProg">文件进度。</param> /// <param name="strmProg">文件流进度。</param> public static void ZipFile(string dirPath, string zipFilePath, Method <string> fileName, Method <int, int> fileProg, Method <int, int> strmProg) { if (string.IsNullOrEmpty(dirPath)) { throw new Exception("压缩路径不能为空!"); } else if (!Directory.Exists(dirPath)) { throw new Exception("未在本地电脑上发现压缩路径!"); } dirPath = dirPath.TrimEnd('\\'); //压缩文件名为空时使用文件夹名+.zip if (string.IsNullOrEmpty(zipFilePath)) { zipFilePath = dirPath + ".zip"; } try { string[] filenames = Directory.GetFiles(dirPath, "*.*", SearchOption.AllDirectories); if (fileProg != null) { fileProg(filenames.Length, 0); } using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFilePath))) { s.SetLevel(9); byte[] buffer = new byte[4096]; for (int i = 0; i < filenames.Length; i++) { string file = filenames[i]; ZipEntry entry = new ZipEntry(file.Substring(dirPath.Length + 1)); if (fileName != null) { fileName(entry.Name); } entry.DateTime = DateTime.Now; s.PutNextEntry(entry); using (FileStream fs = File.OpenRead(file)) { int fsLeng = (int)fs.Length; int ctLeng = 0; int sourceBytes; do { sourceBytes = fs.Read(buffer, 0, buffer.Length); s.Write(buffer, 0, sourceBytes); ctLeng += sourceBytes; if (strmProg != null) { strmProg(fsLeng, ctLeng); } } while (sourceBytes > 0); } if (fileProg != null) { fileProg(filenames.Length, i + 1); } } s.Finish(); s.Close(); } } catch (Exception ex) { throw ex; } }
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> /// Creates the zip file. /// </summary> protected override void ExecuteTask() { ZipOutputStream zOutstream = null; Log(Level.Info, "Zipping {0} files to '{1}'.", ZipFileSets.FileCount, ZipFile.FullName); try { if (!Directory.Exists(ZipFile.DirectoryName)) { Directory.CreateDirectory(ZipFile.DirectoryName); } // set encoding to use for filenames and comment ZipConstants.DefaultCodePage = Encoding.CodePage; zOutstream = new ZipOutputStream(ZipFile.Create()); // set compression level zOutstream.SetLevel(ZipLevel); // set comment if (!String.IsNullOrEmpty(Comment)) { zOutstream.SetComment(Comment); } foreach (ZipFileSet fileset in ZipFileSets) { string basePath = fileset.BaseDirectory.FullName; if (Path.GetPathRoot(basePath) != basePath) { basePath = Path.GetDirectoryName(basePath + Path.DirectorySeparatorChar); } // add files to zip foreach (string file in fileset.FileNames) { // ensure file exists (in case "asis" was used) if (!File.Exists(file)) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, "File '{0}' does not exist.", file), Location); } // the name of the zip entry string entryName; // determine name of the zip entry if (!Flatten && file.StartsWith(basePath)) { entryName = file.Substring(basePath.Length); if (entryName.Length > 0 && entryName[0] == Path.DirectorySeparatorChar) { entryName = entryName.Substring(1); } // remember that directory was added to zip file, so // that we won't add it again later string dir = Path.GetDirectoryName(file); if (_addedDirs[dir] == null) { _addedDirs[dir] = dir; } } else { // flatten directory structure entryName = Path.GetFileName(file); } // add prefix if specified if (fileset.Prefix != null) { entryName = fileset.Prefix + entryName; } // ensure directory separators are understood on linux if (Path.DirectorySeparatorChar == '\\') { entryName = entryName.Replace(@"\", "/"); } // perform duplicate checking if (_fileEntries.ContainsKey(entryName)) { switch (DuplicateHandling) { case DuplicateHandling.Add: break; case DuplicateHandling.Fail: throw new BuildException(string.Format( CultureInfo.InvariantCulture, "Duplicate file '{0}' was found.", entryName), Location.UnknownLocation); case DuplicateHandling.Preserve: // skip current entry continue; default: throw new BuildException(string.Format( CultureInfo.InvariantCulture, "Duplicate value '{0}' is not supported.", DuplicateHandling.ToString()), Location.UnknownLocation); } } // create zip entry ZipEntry entry = new ZipEntry(entryName); // store entry (to allow for duplicate checking) _fileEntries[entryName] = null; // set date/time stamp on zip entry if (Stamp != DateTime.MinValue) { entry.DateTime = Stamp; } else { entry.DateTime = File.GetLastWriteTime(file); } // write file content to stream in small chuncks using (FileStream fs = File.OpenRead(file)) { // set size for backward compatibility with older unzip entry.Size = fs.Length; Log(Level.Verbose, "Adding {0}.", entryName); // write file to zip file zOutstream.PutNextEntry(entry); byte[] buffer = new byte[50000]; while (true) { int bytesRead = fs.Read(buffer, 0, buffer.Length); if (bytesRead == 0) { break; } zOutstream.Write(buffer, 0, bytesRead); } } } // add (possibly empty) directories to zip if (IncludeEmptyDirs) { foreach (string directory in fileset.DirectoryNames) { // skip directories that were already added when the // files were added if (_addedDirs[directory] != null) { continue; } // skip directories that are not located beneath the base // directory if (!directory.StartsWith(basePath) || directory.Length <= basePath.Length) { continue; } // determine zip entry name string entryName = directory.Substring(basePath.Length + 1); // add prefix if specified if (fileset.Prefix != null) { entryName = fileset.Prefix + entryName; } // ensure directory separators are understood on linux if (Path.DirectorySeparatorChar == '\\') { entryName = entryName.Replace(@"\", "/"); } if (!entryName.EndsWith("/")) { // trailing directory signals to #ziplib that we're // dealing with directory entry entryName += "/"; } // create directory entry ZipEntry entry = new ZipEntry(entryName); // set size for backward compatibility with older unzip entry.Size = 0L; // write directory to zip file zOutstream.PutNextEntry(entry); } } } zOutstream.Close(); zOutstream.Finish(); } catch (Exception ex) { // close the zip output stream if (zOutstream != null) { zOutstream.Close(); } // delete the (possibly corrupt) zip file if (ZipFile.Exists) { ZipFile.Delete(); } throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Zip file '{0}' could not be created.", ZipFile.FullName), Location, ex); } finally { CleanUp(); } }
void NewCompress(string sZipFileFullPathName,SPList sList) { SPSecurity.RunWithElevatedPrivileges(delegate { ZipOutputStream zs = new ZipOutputStream(File.Create(sZipFileFullPathName));//D:/project/Dowload/DownLoadFile/1-2-3.zip zs.SetLevel(0); foreach (string sId in sIDS.Split('-')) { SPListItem item = sList.GetItemById(int.Parse(sId)); iParentFolderLength=item.Url.LastIndexOf('/')+1; NewCreateZip(item, zs); } zs.Finish(); zs.Close(); GC.Collect(); }); }
private void writeKML(string filename) { try { writeGPX(filename); } catch { } Color[] colours = { Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Blue, Color.Indigo, Color.Violet, Color.Pink }; AltitudeMode altmode = AltitudeMode.absolute; if (MainV2.comPort.MAV.cs.firmware == MainV2.Firmwares.ArduCopter2) { altmode = AltitudeMode.relativeToGround; // because of sonar, this is both right and wrong. right for sonar, wrong in terms of gps as the land slopes off. } KMLRoot kml = new KMLRoot(); Folder fldr = new Folder("Log"); Style style = new Style(); style.Id = "yellowLineGreenPoly"; style.Add(new LineStyle(HexStringToColor("7f00ffff"), 4)); PolyStyle pstyle = new PolyStyle(); pstyle.Color = HexStringToColor("7f00ff00"); style.Add(pstyle); kml.Document.AddStyle(style); int stylecode = 0xff; int g = -1; foreach (List <Point3D> poslist in position) { g++; if (poslist == null) { continue; } LineString ls = new LineString(); ls.AltitudeMode = altmode; ls.Extrude = true; //ls.Tessellate = true; Coordinates coords = new Coordinates(); coords.AddRange(poslist); ls.coordinates = coords; Placemark pm = new Placemark(); string mode = ""; if (g < modelist.Count) { mode = modelist[g]; } pm.name = g + " Flight Path " + mode; pm.styleUrl = "#yellowLineGreenPoly"; pm.LineString = ls; stylecode = colours[g % (colours.Length - 1)].ToArgb(); Style style2 = new Style(); Color color = Color.FromArgb(0xff, (stylecode >> 16) & 0xff, (stylecode >> 8) & 0xff, (stylecode >> 0) & 0xff); log.Info("colour " + color.ToArgb().ToString("X") + " " + color.ToKnownColor().ToString()); style2.Add(new LineStyle(color, 4)); pm.AddStyle(style2); fldr.Add(pm); } Folder planes = new Folder(); planes.name = "Planes"; fldr.Add(planes); Folder waypoints = new Folder(); waypoints.name = "Waypoints"; fldr.Add(waypoints); LineString lswp = new LineString(); lswp.AltitudeMode = AltitudeMode.relativeToGround; lswp.Extrude = true; Coordinates coordswp = new Coordinates(); foreach (PointLatLngAlt p1 in cmd) { coordswp.Add(new Point3D(p1.Lng, p1.Lat, p1.Alt)); } lswp.coordinates = coordswp; Placemark pmwp = new Placemark(); pmwp.name = "Waypoints"; //pm.styleUrl = "#yellowLineGreenPoly"; pmwp.LineString = lswp; waypoints.Add(pmwp); int a = 0; int l = -1; Model lastmodel = null; foreach (Data mod in flightdata) { l++; if (mod.model.Location.latitude == 0) { continue; } if (lastmodel != null) { if (lastmodel.Location.Equals(mod.model.Location)) { continue; } } Placemark pmplane = new Placemark(); pmplane.name = "Plane " + a; pmplane.visibility = false; Model model = mod.model; model.AltitudeMode = altmode; model.Scale.x = 2; model.Scale.y = 2; model.Scale.z = 2; try { pmplane.description = @"<![CDATA[ <table> <tr><td>Roll: " + model.Orientation.roll + @" </td></tr> <tr><td>Pitch: " + model.Orientation.tilt + @" </td></tr> <tr><td>Yaw: " + model.Orientation.heading + @" </td></tr> <tr><td>WP dist " + mod.ntun[2] + @" </td></tr> <tr><td>tar bear " + mod.ntun[3] + @" </td></tr> <tr><td>nav bear " + mod.ntun[4] + @" </td></tr> <tr><td>alt error " + mod.ntun[5] + @" </td></tr> </table> ]]>"; } catch { } try { pmplane.Point = new KmlPoint((float)model.Location.longitude, (float)model.Location.latitude, (float)model.Location.altitude); pmplane.Point.AltitudeMode = altmode; Link link = new Link(); link.href = "block_plane_0.dae"; model.Link = link; pmplane.Model = model; planes.Add(pmplane); } catch { } // bad lat long value lastmodel = mod.model; a++; } kml.Document.Add(fldr); kml.Save(filename); // create kmz - aka zip file FileStream fs = File.Open(filename.Replace(".log.kml", ".kmz"), FileMode.Create); ZipOutputStream zipStream = new ZipOutputStream(fs); zipStream.SetLevel(9); //0-9, 9 being the highest level of compression zipStream.UseZip64 = UseZip64.Off; // older zipfile // entry 1 string entryName = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction ZipEntry newEntry = new ZipEntry(entryName); newEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(newEntry); // Zip the file in buffered chunks // the "using" will close the stream even if an exception occurs byte[] buffer = new byte[4096]; using (FileStream streamReader = File.OpenRead(filename)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); File.Delete(filename); filename = Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar + "block_plane_0.dae"; // entry 2 entryName = ZipEntry.CleanName(Path.GetFileName(filename)); // Removes drive from name and fixes slash direction newEntry = new ZipEntry(entryName); newEntry.DateTime = DateTime.Now; zipStream.PutNextEntry(newEntry); // Zip the file in buffered chunks // the "using" will close the stream even if an exception occurs buffer = new byte[4096]; using (FileStream streamReader = File.OpenRead(filename)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); zipStream.IsStreamOwner = true; // Makes the Close also Close the underlying stream zipStream.Close(); positionindex = 0; modelist.Clear(); flightdata.Clear(); position = new List <Core.Geometry.Point3D> [200]; cmd.Clear(); }
public void CloseOnlyHandled() { var ms = new MemoryStream(); var s = new ZipOutputStream(ms); s.PutNextEntry(new ZipEntry("dummyfile.tst")); s.Close(); Assert.IsTrue(s.IsFinished, "Output stream should be finished"); }
public static MemberListSyncResult GetMemberListSync(string updatedOn, string grpID, out string filepath) { bool isDataFound = false; string targetPath = ""; try { filepath = ""; MySqlParameter[] param = new MySqlParameter[2]; param[0] = new MySqlParameter("@groupID", grpID); param[1] = new MySqlParameter("@updatedOn", updatedOn); DataSet result = MySqlHelper.ExecuteDataset(GlobalVar.strAppConn, CommandType.StoredProcedure, "V7_USPGetDirectoryListSync", param); DataTable dtnewMember = result.Tables[0]; DataTable dtUpdatedMember = result.Tables[1]; DataTable dtDeletedMember = result.Tables[2]; int dataCount = 10;// Used for paging. DataCount is page size List <MemberDetailsDynamicField> memberList; int Filecounter = 1; int totalrows = dtnewMember.Rows.Count; string FileName = "Dist-" + grpID + DateTime.Now.ToString("ddMMyyyyhhmmsstt"); MemberListSyncResult memListSyncResult = new MemberListSyncResult(); //======================= If total records less than 20 Return Json directly ================================================= int totalRowCount; if (Convert.ToDateTime(updatedOn).Date.ToString("dd/MM/yyyy") == "01/01/1970") { totalRowCount = dtnewMember.Rows.Count; } else { totalRowCount = dtnewMember.Rows.Count + dtUpdatedMember.Rows.Count; } if (totalRowCount <= 20) { //---------------Create array of new members ------------------------------- memberList = new List <MemberDetailsDynamicField>(); if (dtnewMember.Rows.Count > 0) { for (int i = 0; i < dtnewMember.Rows.Count; i++) { MemberDetailsDynamicField memberdtl = GetMemberDtlWithDynamicFeild(dtnewMember.Rows[i]["profileID"].ToString(), grpID); memberList.Add(memberdtl); } } memListSyncResult.NewMemberList = memberList; //---------------Create array of Updated members ------------------------------- memberList = new List <MemberDetailsDynamicField>(); if (dtUpdatedMember.Rows.Count > 0 && Convert.ToDateTime(updatedOn).Date.ToString("dd/MM/yyyy") != "01/01/1970") { for (int i = 0; i < dtUpdatedMember.Rows.Count; i++) { MemberDetailsDynamicField memberdtl = GetMemberDtlWithDynamicFeild(dtUpdatedMember.Rows[i]["profileID"].ToString(), grpID); memberList.Add(memberdtl); } } memListSyncResult.UpdatedMemberList = memberList; //-----------------Deleted member -------------------------------------------------- string deletedProfiles = ""; if (dtDeletedMember != null && Convert.ToDateTime(updatedOn).Date.ToString("dd/MM/yyyy") != "01/01/1970") { if (!string.IsNullOrEmpty(dtDeletedMember.Rows[0]["profileID"].ToString())) { deletedProfiles = dtDeletedMember.Rows[0]["profileID"].ToString(); } } memListSyncResult.DeletedMemberList = deletedProfiles; } //======================= If Records Greater than 20 Return Zip File ================================================= else { if (dtnewMember.Rows.Count > 0) { memberList = new List <MemberDetailsDynamicField>(); for (int i = 0; i < totalrows; i++) { if (i < dataCount) // add object to page { try { MemberDetailsDynamicField memberdtl = GetMemberDtlWithDynamicFeild(dtnewMember.Rows[i]["profileID"].ToString(), grpID); memberList.Add(memberdtl); MemberDetails memberDtl = new MemberDetails(); memberDtl.MemberDetail = memberList; // For each page create a seperate json file if (i == dataCount - 1 || i == totalrows - 1) { // create a file string json = JsonConvert.SerializeObject(memberDtl); //write string to file string Path = ConfigurationManager.AppSettings["imgPathSave"] + "TempDocuments\\DirectoryData\\Profile" + FileName; if (!Directory.Exists(Path)) { Directory.CreateDirectory(Path); } if (!Directory.Exists(Path + "/NewMembers")) { Directory.CreateDirectory(Path + "/NewMembers"); } System.IO.File.WriteAllText(Path + "/NewMembers/New" + Filecounter + ".json", json); Filecounter++; } } catch { } } else { // reset member list for next page memberList = new List <MemberDetailsDynamicField>(); dataCount = dataCount + 10; i--; } } } if (dtUpdatedMember.Rows.Count > 0 && Convert.ToDateTime(updatedOn).Date.ToString("dd/MM/yyyy") != "01/01/1970") { dataCount = 10; // Used for paging. dataCount is page size memberList = new List <MemberDetailsDynamicField>(); Filecounter = 1; totalrows = dtUpdatedMember.Rows.Count; for (int i = 0; i < totalrows; i++) { if (i < dataCount) { try { MemberDetailsDynamicField memberdtl = GetMemberDtlWithDynamicFeild(dtUpdatedMember.Rows[i]["profileID"].ToString(), grpID); memberList.Add(memberdtl); MemberDetails memberDtl = new MemberDetails(); memberDtl.MemberDetail = memberList; // For each page create a seperate json file if (i == dataCount - 1 || i == totalrows - 1) { // create a file string json = JsonConvert.SerializeObject(memberDtl); //write string to file string Path = ConfigurationManager.AppSettings["imgPathSave"] + "TempDocuments\\DirectoryData\\Profile" + FileName; if (!Directory.Exists(Path)) { Directory.CreateDirectory(Path); } if (!Directory.Exists(Path + "/UpdatedMembers")) { Directory.CreateDirectory(Path + "/UpdatedMembers"); } System.IO.File.WriteAllText(Path + "/UpdatedMembers/Update" + Filecounter + ".json", json); Filecounter++; } } catch { } } else { // reset member list for next page memberList = new List <MemberDetailsDynamicField>(); dataCount = dataCount + 10; i--; } } } if (dtDeletedMember != null && Convert.ToDateTime(updatedOn).Date.ToString("dd/MM/yyyy") != "01/01/1970") { if (!string.IsNullOrEmpty(dtDeletedMember.Rows[0]["profileID"].ToString())) { string deletedProfiles = dtDeletedMember.Rows[0]["profileID"].ToString(); string Path = ConfigurationManager.AppSettings["imgPathSave"] + "TempDocuments\\DirectoryData\\Profile" + FileName; if (!Directory.Exists(Path)) { Directory.CreateDirectory(Path); } if (!Directory.Exists(Path + "/DeletedMembers")) { Directory.CreateDirectory(Path + "/DeletedMembers"); } System.IO.File.WriteAllText(Path + "/DeletedMembers/Delete" + Filecounter + ".txt", deletedProfiles); } } string zipFolderPath = ConfigurationManager.AppSettings["imgPathSave"] + "TempDocuments\\DirectoryData\\Profile" + FileName; if (Directory.Exists(zipFolderPath)) { targetPath = ConfigurationManager.AppSettings["imgPathSave"] + "TempDocuments\\DirectoryData\\Profile" + FileName + ".zip"; zos = new ZipOutputStream(File.Create(targetPath)); zos.UseZip64 = UseZip64.Off; strBaseDir = zipFolderPath + "\\"; AddZipEntry(strBaseDir); zos.Finish(); zos.Close(); isDataFound = true; } if (isDataFound) { filepath = ConfigurationManager.AppSettings["imgPath"] + "TempDocuments/DirectoryData/Profile" + FileName + ".zip"; } } return(memListSyncResult); } catch { throw; } }
public void StoredNonSeekableConvertToDeflate() { var ms = new MemoryStreamWithoutSeek(); var outStream = new ZipOutputStream(ms); outStream.SetLevel(8); Assert.AreEqual(8, outStream.GetLevel(), "Compression level invalid"); var entry = new ZipEntry("1.tst"); entry.CompressionMethod = CompressionMethod.Stored; outStream.PutNextEntry(entry); Assert.AreEqual(0, outStream.GetLevel(), "Compression level invalid"); AddRandomDataToEntry(outStream, 100); entry = new ZipEntry("2.tst"); entry.CompressionMethod = CompressionMethod.Deflated; outStream.PutNextEntry(entry); Assert.AreEqual(8, outStream.GetLevel(), "Compression level invalid"); AddRandomDataToEntry(outStream, 100); outStream.Close(); }
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; }
// Save mosaic data. internal void SaveMosaicCacheFile() { if (this.threadController != null) { this.threadController.ReportThreadStarted(this, "Saving Tiles"); } string tempFilePath = Path.GetTempFileName(); try { this.oZipStream = new ZipOutputStream(System.IO.File.Create(tempFilePath)); } catch (Exception e) { MessageBox.Show(e.Message); return; } this.oZipStream.SetLevel(2); // 9 = maximum compression level ZipEntry oZipEntry = new ZipEntry("info.txt"); this.oZipStream.PutNextEntry(oZipEntry); StreamWriter sw = new StreamWriter(oZipStream); TileSaver.SaveMosaicHeader(MosaicWindow.MosaicInfo, sw); ThumbnailMapCollection mapCollection = new ThumbnailMapCollection(MosaicWindow.MosaicInfo.Items[0].Thumbnail.Width, MosaicWindow.MosaicInfo.Items[0].Thumbnail.Height); mapCollection.MapFilled += new ThumbnailMapCollectionEventHandler(OnMapFilled); int count = 1; int requiredMaps = (MosaicWindow.MosaicInfo.Items.Count / ThumbnailMap.MaxSize) + 1; foreach (Tile tile in MosaicWindow.MosaicInfo.Items) // For each file, generate a zipentry { if (this.threadController.ThreadAborted) { return; } mapCollection.AddThumbnail(tile); if (this.threadController != null) { threadController.ReportThreadPercentage(this, "Creating Tile Maps", count++, MosaicWindow.MosaicInfo.Items.Count); } } // Final map may not get completly filled // if not then save it here if (mapCollection.Maps.Count <= requiredMaps) { ThumbnailMapCollectionEventArgs thumbnailEventArgs = new ThumbnailMapCollectionEventArgs(mapCollection.Last); OnMapFilled(mapCollection, thumbnailEventArgs); } mapCollection.Dispose(); oZipStream.Finish(); oZipStream.Dispose(); oZipStream.Close(); try { File.Delete(MosaicWindow.MosaicInfo.TileReader.GetCacheFilePath()); File.Copy(tempFilePath, MosaicWindow.MosaicInfo.TileReader.GetCacheFilePath()); } catch (Exception) { } //File.SetAttributes(this.filePath, FileAttributes.Hidden); if (this.threadController != null) { this.threadController.ReportThreadCompleted(this, "Cache Saved", false); } GC.Collect(); }
public string GENERAPDFSGA(int wr_id, string sga, string username) { System.Web.UI.Page pg = new Page(); string pathRptSource; ReportDocument crReportDocument = new ReportDocument(); Classi.ManCorrettiva.MANCORRETTIVASFOGLIARDL _RichiestaIntervento = new Classi.ManCorrettiva.MANCORRETTIVASFOGLIARDL(); DataSet Ds = _RichiestaIntervento.ReportSGA(wr_id); dsRapportino dsP = new dsRapportino(); int i = 0; for (i = 0; i <= Ds.Tables[0].Rows.Count - 1; i++) { dsP.Tables["sga"].ImportRow(Ds.Tables[0].Rows[i]); } pathRptSource = pg.Server.MapPath("../Report/RptSGA1.rpt"); crReportDocument.Load(pathRptSource); crReportDocument.SetDataSource(dsP); //string Fname = pg.Server.MapPath("../Report/" + pg.Session.SessionID.ToString() + ".pdf");// ExportOptions optExp; DiskFileDestinationOptions optDsk = new DiskFileDestinationOptions(); PdfRtfWordFormatOptions optPdfRtf = new PdfRtfWordFormatOptions(); optExp = crReportDocument.ExportOptions; optExp.ExportFormatType = ExportFormatType.PortableDocFormat; optExp.FormatOptions = optPdfRtf; optExp.ExportDestinationType = ExportDestinationType.DiskFile; //-----inserire nome del file nuovo string STORENAME = "PACK_TRACCIA_DOC.SP_INS_SGA"; conn.Open(); System.Data.OracleClient.OracleCommand cmd = new OracleCommand(); cmd.Connection = conn; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = STORENAME; OracleParameter par1 = new OracleParameter(); par1.ParameterName = "p_id_wr"; par1.OracleType = System.Data.OracleClient.OracleType.Number; par1.Direction = ParameterDirection.Input; par1.Value = wr_id; par1.Size = 100; cmd.Parameters.Add(par1); OracleParameter par2 = new OracleParameter(); par2.ParameterName = "p_user"; par2.OracleType = System.Data.OracleClient.OracleType.VarChar; par2.Direction = ParameterDirection.Input; par2.Size = 50; par2.Value = username; cmd.Parameters.Add(par2); OracleParameter par3 = new OracleParameter(); par3.ParameterName = "p_sga"; par3.OracleType = System.Data.OracleClient.OracleType.VarChar; par3.Direction = ParameterDirection.Input; par3.Size = 100; par3.Value = sga; cmd.Parameters.Add(par3); OracleParameter par4 = new OracleParameter(); par4.ParameterName = "p_codice"; par4.OracleType = System.Data.OracleClient.OracleType.VarChar; par4.Direction = ParameterDirection.Output; par4.Size = 50; par4.Value = ""; cmd.Parameters.Add(par4); cmd.ExecuteNonQuery(); string NOMESGA = cmd.Parameters["p_codice"].Value.ToString(); // OracleDataReader rdr = cmd.ExecuteReader(); // string pr=rdr.GetString(); //string pr=cmd.ExecuteScalar(); conn.Close(); cmd.Dispose(); //@"C:\Inetpub\wwwroot\RL\Doc_DB\" //optDsk.DiskFileName = pathRptSource+sga+".pdf"; optDsk.DiskFileName = @System.Configuration.ConfigurationSettings.AppSettings["DIRSGA"] + NOMESGA; //Fname; optExp.DestinationOptions = optDsk; crReportDocument.Export(); string FileZip = Path.GetDirectoryName(optDsk.DiskFileName) + @"\" + Path.GetFileNameWithoutExtension(optDsk.DiskFileName) + ".zip"; if (File.Exists(FileZip)) { File.Delete(FileZip); } ZipOutputStream s = new ZipOutputStream(File.Create(FileZip)); s.SetLevel(5); // 0 - store only to 9 - FileStream fs = File.OpenRead(optDsk.DiskFileName); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); ZipEntry entry = new ZipEntry(Path.GetFileName(optDsk.DiskFileName)); s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); s.Finish(); s.Close(); fs.Close(); TheSite.Classi.MailSend mail = new TheSite.Classi.MailSend(); //mail.SendMail(optDsk.DiskFileName,wr_id,DocType.SGA); mail.SendMail(FileZip, wr_id, DocType.SGA); return(optDsk.DiskFileName); }
// [Test] // [Category("Zip")] // [Category("CreatesTempFile")] public void MakeLargeZipFile() { string tempFile = null; try { // tempFile = Path.GetTempPath(); tempFile = @"g:\\tmp"; } catch (SecurityException) { } Assert.IsNotNull(tempFile, "No permission to execute this test?"); if (tempFile != null) { const int blockSize = 4096; var data = new byte[blockSize]; byte nextValue = 0; for (var i = 0; i < blockSize; ++i) { nextValue = ScatterValue(nextValue); data[i] = nextValue; } tempFile = Path.Combine(tempFile, "SharpZipTest.Zip"); Console.WriteLine("Starting at {0}", DateTime.Now); try { // MakeZipFile(tempFile, new String[] {"1", "2" }, int.MaxValue, "C1"); using (var fs = File.Create(tempFile)) { var zOut = new ZipOutputStream(fs); zOut.SetLevel(4); const int TargetFiles = 8100; for (var i = 0; i < TargetFiles; ++i) { var e = new ZipEntry(i.ToString()); e.CompressionMethod = CompressionMethod.Stored; zOut.PutNextEntry(e); for (var block = 0; block < 128; ++block) { zOut.Write(data, 0, blockSize); } } zOut.Close(); fs.Close(); TestLargeZip(tempFile, TargetFiles); } } finally { Console.WriteLine("Starting at {0}", DateTime.Now); // File.Delete(tempFile); } } }