private void zip(string strFile, ZipOutputStream s, string staticFile) { if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar) strFile += Path.DirectorySeparatorChar; Crc32 crc = new Crc32(); string[] filenames = Directory.GetFileSystemEntries(strFile); foreach (string file in filenames) { if (Directory.Exists(file)) { zip(file, s, staticFile); } else // 否则直接压缩文件 { //打开压缩文件 FileStream fs = File.OpenRead(file); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); string tempfile = file.Substring(staticFile.LastIndexOf("\\") + 1); ZipEntry entry = new ZipEntry(tempfile); 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); } } }
/// <summary> /// 压缩单个文件 /// </summary> /// <param name="fileToZip">要进行压缩的文件名</param> /// <param name="zipedFile">压缩后生成的压缩文件名</param> /// <param name="level">压缩等级</param> /// <param name="password">密码</param> /// <param name="onFinished">压缩完成后的代理</param> public static void ZipFile(string fileToZip, string zipedFile, string password = "", int level = 5, OnFinished onFinished = null) { //如果文件没有找到,则报错 if (!File.Exists(fileToZip)) throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!"); using (FileStream fs = File.OpenRead(fileToZip)) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); fs.Close(); using (FileStream ZipFile = File.Create(zipedFile)) { using (ZipOutputStream ZipStream = new ZipOutputStream(ZipFile)) { string fileName = fileToZip.Substring(fileToZip.LastIndexOf("/") + 1); ZipEntry ZipEntry = new ZipEntry(fileName); ZipStream.PutNextEntry(ZipEntry); ZipStream.SetLevel(level); ZipStream.Password = password; ZipStream.Write(buffer, 0, buffer.Length); ZipStream.Finish(); ZipStream.Close(); if (null != onFinished) onFinished(); } } } }
public static void Compress(string path, ZipOutputStream output, string relativePath) { if (!string.IsNullOrEmpty(relativePath) && !relativePath.EndsWith("\\")) { relativePath += "\\"; } if (Directory.Exists(path)) { FileSystemInfo[] fsis = new DirectoryInfo(path).GetFileSystemInfos(); ZipEntry entry = new ZipEntry(relativePath + Path.GetFileName(path) + "/"); entry.DateTime = DateTime.Now; output.PutNextEntry(entry); foreach (FileSystemInfo fsi in fsis) { Compress(path + "\\" + fsi.Name, output, relativePath + Path.GetFileName(path)); } } else { Crc32 crc = new Crc32(); //打开压缩文件 Stream fs = File.Open(path, FileMode.Open, FileAccess.Read); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); ZipEntry entry = new ZipEntry(relativePath + Path.GetFileName(path)); entry.DateTime = DateTime.Now; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; output.PutNextEntry(entry); output.Write(buffer, 0, buffer.Length); } }
public static void ZipFiles(string inputFolderPath, string outPath, string password) { ArrayList ar = GenerateFileList(inputFolderPath); // generate file list int TrimLength = (Directory.GetParent(inputFolderPath)).ToString().Length; // find number of chars to remove // from orginal file path TrimLength += 1; //remove '\' FileStream ostream; byte[] obuffer; ZipOutputStream oZipStream = new ZipOutputStream(File.Create(outPath)); // create zip stream if (password != null && password != String.Empty) oZipStream.Password = password; oZipStream.SetLevel(9); // maximum compression ZipEntry oZipEntry; foreach (string Fil in ar) // for each file, generate a zipentry { oZipEntry = new ZipEntry(Fil.Remove(0, TrimLength)); oZipStream.PutNextEntry(oZipEntry); if (!Fil.EndsWith(@"/")) // if a file ends with '/' its a directory { ostream = File.OpenRead(Fil); obuffer = new byte[ostream.Length]; ostream.Read(obuffer, 0, obuffer.Length); oZipStream.Write(obuffer, 0, obuffer.Length); ostream.Close(); } } oZipStream.Finish(); oZipStream.Close(); }
private static byte[] Compression(byte[] bytes) { MemoryStream ms = new MemoryStream(); ZipOutputStream zos = new ZipOutputStream(ms); ZipEntry ze = new ZipEntry(ConfigConst.ZipEntryName); zos.PutNextEntry(ze); zos.SetLevel(9); zos.Write(bytes, 0, bytes.Length);//写入压缩文件 zos.Close(); return ms.ToArray(); }
public static void WriteZipFile(List<FileDetails> filesToZip, string path,string manifestPath,string manifest ) { int compression = 9; FileDetails fd = new FileDetails(manifest, manifestPath,manifestPath); filesToZip.Insert(0,fd); foreach (FileDetails obj in filesToZip) if (!File.Exists(obj.FilePath)) throw new ArgumentException(string.Format("The File {0} does not exist!", obj.FileName)); Object _locker=new Object(); lock(_locker) { Crc32 crc32 = new Crc32(); ZipOutputStream stream = new ZipOutputStream(File.Create(path)); stream.SetLevel(compression); for (int i = 0; i < filesToZip.Count; i++) { ZipEntry entry = new ZipEntry(filesToZip[i].FolderInfo + "/" + filesToZip[i].FileName); entry.DateTime = DateTime.Now; if (i == 0) { entry = new ZipEntry(manifest); } using (FileStream fs = File.OpenRead(filesToZip[i].FilePath)) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); entry.Size = fs.Length; fs.Close(); crc32.Reset(); crc32.Update(buffer); entry.Crc = crc32.Value; stream.PutNextEntry(entry); stream.Write(buffer, 0, buffer.Length); } } stream.Finish(); stream.Close(); DeleteManifest(manifestPath); } }
internal override bool Evaluate(ZipEntry entry) { bool result = Left.Evaluate(entry); switch (Conjunction) { case LogicalConjunction.AND: if (result) result = Right.Evaluate(entry); break; case LogicalConjunction.OR: if (!result) result = Right.Evaluate(entry); break; case LogicalConjunction.XOR: result ^= Right.Evaluate(entry); break; } return result; }
public static void Main(string[] args) { string[] filenames = Directory.GetFiles(args[0]); Crc32 crc = new Crc32(); ZipOutputStream s = new ZipOutputStream(File.Create(args[1])); s.SetLevel(6); // 0 - store only to 9 - means best compression foreach (string file in filenames) { FileStream fs = File.OpenRead(file); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); ZipEntry entry = new ZipEntry(file); 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; s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); } s.Finish(); s.Close(); }
/// <summary> /// 压缩单个文件 /// </summary> /// <param name="fileToZip">要压缩的文件</param> /// <param name="zipedFile">压缩后的文件</param> /// <param name="compressionLevel">压缩等级</param> /// <param name="blockSize">每次写入大小</param> /// <param name="onFinished">压缩完成后的委托</param> public static void ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize, string password, OnFinished onFinished) { //如果文件没有找到,则报错 if (File.Exists(fileToZip)) throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!"); using (FileStream zipFile = File.Create(zipedFile)) { using (ZipOutputStream zipStream = new ZipOutputStream(zipFile)) { using (FileStream streamToZip = new FileStream(fileToZip, FileMode.Open, FileAccess.Read)) { string fileName = fileToZip.Substring(fileToZip.LastIndexOf("/") + 1); ZipEntry zipEntry = new ZipEntry(fileName); zipStream.PutNextEntry(zipEntry); zipStream.SetLevel(compressionLevel); byte[] buffer = new byte[blockSize]; int sizeRead = 0; try { do { sizeRead = streamToZip.Read(buffer, 0, buffer.Length); zipStream.Write(buffer, 0, sizeRead); } while (sizeRead > 0); } catch (System.Exception ex) { throw ex; } streamToZip.Close(); } zipStream.Finish(); zipStream.Close(); } zipFile.Close(); if (null != onFinished) onFinished(); } }
/// <summary> /// Архивирует данные одного потока в другой поток. /// </summary> /// <param name="inputStream">Входной поток.</param> /// <param name="outputStream">Выходной поток.</param> /// <param name="entryFileName">Имя файла, которое будет помещено в выходном архиве.</param> public static void ZipData( Stream inputStream, Stream outputStream, string entryFileName ) { Crc32 crc = new Crc32(); ZipOutputStream zipStream = new ZipOutputStream( outputStream ); // начинаем архивировать zipStream.SetLevel( 9 ); // уровень сжатия long length = inputStream.Length; byte[] buffer = new byte[length]; inputStream.Read( buffer, 0, buffer.Length ); ZipEntry entry = new ZipEntry( entryFileName ); entry.DateTime = DateTime.Now; entry.Size = length; crc.Reset(); crc.Update( buffer ); entry.Crc = crc.Value; zipStream.PutNextEntry( entry ); zipStream.Write( buffer, 0, buffer.Length ); zipStream.Finish(); }
public void Create_WithSpecifiedCodepage() { int i; CodepageTrial[] trials = { new CodepageTrial("big5", "弹出应用程序{0:D3}.bin", true), new CodepageTrial("big5", "您好{0:D3}.bin", false), new CodepageTrial("gb2312", "弹出应用程序{0:D3}.bin", false), new CodepageTrial("gb2312", "您好{0:D3}.bin", false), // insert other trials here.?? }; for (int k = 0; k < trials.Length; k++) { TestContext.WriteLine(""); TestContext.WriteLine("---------------------Trial {0}....", k); TestContext.WriteLine("---------------------codepage: {0}....", trials[k].codepage); // create the subdirectory string subdir = Path.Combine(TopLevelDir, String.Format("trial{0}-files", k)); Directory.CreateDirectory(subdir); // create a bunch of files int numFiles = _rnd.Next(3) + 3; string[] filesToZip = new string[numFiles]; for (i = 0; i < numFiles; i++) { filesToZip[i] = Path.Combine(subdir, String.Format(trials[k].filenameFormat, i)); TestUtilities.CreateAndFillFileBinary(filesToZip[i], _rnd.Next(5000) + 2000); } Directory.SetCurrentDirectory(subdir); // three cases: one for old-style // ProvisionalAlternateEncoding, one for "AsNecessary" // and one for "Always" for (int j = 0; j < 3; j++) { // select the name of the zip file string zipFileToCreate = Path.Combine(TopLevelDir, String.Format("WithSpecifiedCodepage_{0}_{1}_{2}.zip", k, j, trials[k].codepage)); TestContext.WriteLine(""); TestContext.WriteLine("---------------Creating zip, trial ({0},{1})....", k, j); using (ZipFile zip1 = new ZipFile()) { switch (j) { case 0: #pragma warning disable 618 zip1.ProvisionalAlternateEncoding = System.Text.Encoding.GetEncoding(trials[k].codepage); #pragma warning restore 618 break; case 1: zip1.AlternateEncoding = System.Text.Encoding.GetEncoding(trials[k].codepage); zip1.AlternateEncodingUsage = ZipOption.AsNecessary; break; case 2: zip1.AlternateEncoding = System.Text.Encoding.GetEncoding(trials[k].codepage); zip1.AlternateEncodingUsage = ZipOption.Always; break; } for (i = 0; i < filesToZip.Length; i++) { TestContext.WriteLine("adding entry {0}", filesToZip[i]); // use the local filename (not fully qualified) ZipEntry e = zip1.AddFile(filesToZip[i], ""); e.Comment = String.Format("This entry was encoded in the {0} codepage", trials[k].codepage); } zip1.Save(zipFileToCreate); } TestContext.WriteLine("\n---------------------Extracting...."); Directory.SetCurrentDirectory(TopLevelDir); try { // verify the filenames are (or are not) unicode var options = new ReadOptions { Encoding = System.Text.Encoding.GetEncoding(trials[k].codepage) }; using (ZipFile zip2 = FileSystemZip.Read(zipFileToCreate, options)) { foreach (ZipEntry e in zip2) { TestContext.WriteLine("found entry {0}", e.FileName); e.Extract(String.Format("trial{0}-{1}-{2}-extract", k, j, trials[k].codepage)); } } } catch (Exception e1) { if (trials[k].exceptionExpected) { TestContext.WriteLine("caught expected exception"); } else { throw new System.Exception("while extracting", e1); } } } } TestContext.WriteLine("\n---------------------Done."); }
internal override bool Evaluate(ZipEntry entry) { FileAttributes fileAttrs = entry.Attributes; return _Evaluate(fileAttrs); }
internal abstract bool Evaluate(ZipEntry entry);
private IAlbum VerifyAlbumExistsAndReturnReference(ZipEntry zipContentFile, IAlbum rootParentAlbum) { // Get the directory path of the next file or directory within the zip file. // Ex: album1\album2\album3, album1 string zipDirectoryPath = Path.GetDirectoryName(zipContentFile.Name); string[] directoryNames = zipDirectoryPath.Split(new char[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries); string albumFullPhysicalPath = rootParentAlbum.FullPhysicalPathOnDisk; IAlbum currentAlbum = rootParentAlbum; foreach (string directoryNameFromZip in directoryNames) { string shortenedDirName = GetPreviouslyCreatedTruncatedAlbumName(albumFullPhysicalPath, directoryNameFromZip); // Ex: c:\inetpub\wwwroot\galleryserver\mypics\2006\album1 albumFullPhysicalPath = System.IO.Path.Combine(albumFullPhysicalPath, shortenedDirName); IAlbum newAlbum = null; if (Directory.Exists(albumFullPhysicalPath)) { // Directory exists, so there is probably an album corresponding to it. Find it. IGalleryObjectCollection childGalleryObjects = currentAlbum.GetChildGalleryObjects(GalleryObjectType.Album); foreach (IGalleryObject childGalleryObject in childGalleryObjects) { if (childGalleryObject.FullPhysicalPathOnDisk == albumFullPhysicalPath) { newAlbum = childGalleryObject as Album; break; } } if (newAlbum == null) { // No album in the database matches that directory. Add it. // Before we add the album, we need to make sure the user has permission to add the album. Check if user // is authenticated and if the current album is the one passed into this method. It can be assumed that any // other album we encounter has been created by this method and we checked for permission when it was created. if (this._isAuthenticated && (currentAlbum.Id == rootParentAlbum.Id)) SecurityManager.ThrowIfUserNotAuthorized(SecurityActions.AddChildAlbum, this._roles, currentAlbum.Id, this._isAuthenticated, currentAlbum.IsPrivate); newAlbum = Factory.CreateAlbumInstance(); newAlbum.Parent = currentAlbum; newAlbum.IsPrivate = currentAlbum.IsPrivate; newAlbum.DirectoryName = directoryNameFromZip; HelperFunctions.UpdateAuditFields(newAlbum, this._userName); newAlbum.Save(); } } else { // The directory doesn't exist. Create an album. // Before we add the album, we need to make sure the user has permission to add the album. Check if user // is authenticated and if the current album is the one passed into this method. It can be assumed that any // other album we encounter has been created by this method and we checked for permission when it was created. if (this._isAuthenticated && (currentAlbum.Id == rootParentAlbum.Id)) SecurityManager.ThrowIfUserNotAuthorized(SecurityActions.AddChildAlbum, this._roles, currentAlbum.Id, this._isAuthenticated, currentAlbum.IsPrivate); newAlbum = Factory.CreateAlbumInstance(); newAlbum.IsPrivate = currentAlbum.IsPrivate; newAlbum.Parent = currentAlbum; newAlbum.Title = directoryNameFromZip; HelperFunctions.UpdateAuditFields(newAlbum, this._userName); newAlbum.Save(); // If the directory name written to disk is different than the name from the zip file, add it to // our hash table. if (!directoryNameFromZip.Equals(newAlbum.DirectoryName)) { this._albumAndDirectoryNamesLookupTable.Add(Path.Combine(currentAlbum.FullPhysicalPathOnDisk, directoryNameFromZip), Path.Combine(currentAlbum.FullPhysicalPathOnDisk, newAlbum.DirectoryName)); } } currentAlbum = newAlbum; } return currentAlbum; }
private void CompressFolder(string path, ZipOutputStream zipStream, int folderOffset) { string[] files = Directory.GetFiles(path); foreach (string filename in files) { 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(); } string[] folders = Directory.GetDirectories(path); foreach (string folder in folders) { CompressFolder(folder, zipStream, folderOffset); } }
public void UnLoad(Stream mainStream) { using (var memoryStream = new MemoryStream()) { //xmlContent.For xmlContent.Save(memoryStream); memoryStream.Close(); files[fContent]["Data"] = memoryStream.ToArray();// System.Text.Encoding.UTF8.GetBytes(sb.ToString()) } using (var memoryStream = new MemoryStream()) { xmlManifest.Save(memoryStream); memoryStream.Close(); files[fMainfest]["Data"] = memoryStream.ToArray(); } if (xmlMeta.DocumentElement != null) { using (var memoryStream = new MemoryStream()) { xmlMeta.Save(memoryStream); memoryStream.Close(); files[fMeta]["Data"] = memoryStream.ToArray(); } } if (xmlSettings.DocumentElement != null) { using (var memoryStream = new MemoryStream()) { xmlSettings.Save(memoryStream); memoryStream.Close(); files[fSetting]["Data"] = memoryStream.ToArray(); } } using (var memoryStream = new MemoryStream()) { xmlStyles.Save(memoryStream); memoryStream.Close(); files[fStyles]["Data"] = memoryStream.ToArray(); } using (var zo = new ZipOutputStream(mainStream)) { zo.UseZip64 = UseZip64.Off; foreach (string key in files.Keys) { ZipEntry ze = new ZipEntry(key); zo.PutNextEntry(ze); if (!(bool)files[key]["IsDirectory"]) { zo.Write((byte[])files[key]["Data"], 0, ((byte[])files[key]["Data"]).Length); } } zo.Finish(); mainStream.Flush(); } }
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 bool LoadSceneFile(string scenefilename) { try { UVDLPApp.Instance().SceneFileName = scenefilename; LoadManifest(scenefilename); using (ZipFile mZip = ZipFile.Read(scenefilename)) { //examine manifest //find the node with models XmlNode topnode = mManifest.m_toplevel; //load gcode if present XmlNode gcn = mManifest.FindSection(mManifest.m_toplevel, "GCode"); //get the name of the gcode file string gcodename = mManifest.GetString(gcn, "name", "none"); if (!gcodename.Equals("none")) { //open the zip ZipEntry gcodeentry = mZip[gcodename]; MemoryStream gcstr = new MemoryStream(); gcodeentry.Extract(gcstr); //rewind to beginning gcstr.Seek(0, SeekOrigin.Begin); GCodeFile gcf = new GCodeFile(gcstr); UVDLPApp.Instance().m_gcode = gcf; UVDLPApp.Instance().RaiseAppEvent(eAppEvent.eGCodeLoaded, "GCode Loaded "); } else { UVDLPApp.Instance().m_gcode = new GCodeFile(""); // empty } // load slice profile if present XmlNode spn = mManifest.FindSection(mManifest.m_toplevel, "SliceProfile"); string sliceprofilename = mManifest.GetString(spn, "name", "none"); if (!sliceprofilename.Equals("none")) { ZipEntry gcodeentry = mZip[sliceprofilename]; MemoryStream gcstr = new MemoryStream(); gcodeentry.Extract(gcstr); //rewind to beginning gcstr.Seek(0, SeekOrigin.Begin); //GCodeFile gcf = new GCodeFile(gcstr); UVDLPApp.Instance().m_buildparms = new SliceBuildConfig(); UVDLPApp.Instance().m_buildparms.Load(gcstr, sliceprofilename); //create a new slice file based off of the build and slicing parameters UVDLPApp.Instance().m_slicefile = new SliceFile(UVDLPApp.Instance().m_buildparms); UVDLPApp.Instance().m_slicefile.m_mode = SliceFile.SFMode.eLoaded; UVDLPApp.Instance().m_slicer.SliceFile = UVDLPApp.Instance().m_slicefile; UVDLPApp.Instance().m_slicefile.NumSlices = UVDLPApp.Instance().m_slicer.GetNumberOfSlices(UVDLPApp.Instance().m_buildparms); //raise the event to indicate it's loaded UVDLPApp.Instance().RaiseAppEvent(eAppEvent.eSliceProfileChanged, "Slice Profile loaded"); UVDLPApp.Instance().RaiseAppEvent(eAppEvent.eSlicedLoaded, "Slice Profile loaded"); } // now load the models XmlNode models = mManifest.FindSection(topnode, "Models"); List <XmlNode> modelnodes = mManifest.FindAllChildElement(models, "model"); // bool supportLoaded = false; foreach (XmlNode nd in modelnodes) { string name = mManifest.GetString(nd, "name", "noname"); string modstlname = name + ".stl"; int tag = mManifest.GetInt(nd, "tag", 0); ZipEntry modelentry = mZip[modstlname]; // the model name will have the _XXXX on the end with the stl extension MemoryStream modstr = new MemoryStream(); modelentry.Extract(modstr); //rewind to beginning modstr.Seek(0, SeekOrigin.Begin); //fix the name name = name.Substring(0, name.Length - 5);// get rid of the _XXXX at the end string parentName = mManifest.GetString(nd, "parent", "noname"); Object3d obj, tmpObj; switch (tag) { case Object3d.OBJ_SUPPORT: case Object3d.OBJ_SUPPORT_BASE: if (tag == Object3d.OBJ_SUPPORT) { obj = (Object3d)(new Support()); } else { obj = (Object3d)(new SupportBase()); } //load the model obj.LoadSTL_Binary(modstr, name); //add to the 3d engine UVDLPApp.Instance().m_engine3d.AddObject(obj); //set the tag obj.tag = tag; obj.SetColor(System.Drawing.Color.Yellow); //find and set the parent tmpObj = UVDLPApp.Instance().m_engine3d.Find(parentName); if (tmpObj != null) { tmpObj.AddSupport(obj); } //supportLoaded = true; break; default: //load as normal object obj = new Object3d(); //load the model obj.LoadSTL_Binary((MemoryStream)modstr, name); //add to the 3d engine UVDLPApp.Instance().m_engine3d.AddObject(obj); //set the tag obj.tag = tag; break; } } } UVDLPApp.Instance().RaiseAppEvent(eAppEvent.eModelAdded, "Scene loaded"); return(true); } catch (Exception ex) { DebugLogger.Instance().LogError(ex); return(false); } }
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 }
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 архив } } }
public void LoadXML() { ZipFile zf = null; try { FileStream fs = File.OpenRead(Path); zf = new ZipFile(fs); int idx = zf.FindEntry(DefaultMetaFileName, false); ZipEntry metaFile = zf[idx]; using (XmlReader r = GetXMLReader(zf.GetInputStream(metaFile))) { Version currentVersion = null; while (r.Read()) { if (r.NodeType == XmlNodeType.Element && r.Name == "File") { } else if (r.NodeType == XmlNodeType.Element && r.Name == "Versions") { } else if (r.NodeType == XmlNodeType.Element && r.Name == "Version") { currentVersion = new Version(); currentVersion.Key = DateTime.Parse(r.GetAttribute("Key")); currentVersion.Mark = r.GetAttribute("Mark"); _codeFile._versions.AddLast(currentVersion); } else if (r.NodeType == XmlNodeType.EndElement && r.Name == "Version") { currentVersion = null; } // Checkboxes else if (r.NodeType == XmlNodeType.Element && r.Name == "Checkboxes") { } else if (r.NodeType == XmlNodeType.Element && r.Name == "Checkbox") { int offset = Convert.ToInt32(r.GetAttribute("Offset")); currentVersion.Checkboxes.Add(currentVersion.Document.CreateAnchor(offset)); } // Comments else if (r.NodeType == XmlNodeType.Element && r.Name == "Comments") { } else if (r.NodeType == XmlNodeType.Element && r.Name == "Comment") { string text = r.GetAttribute("Text"); int offset = Convert.ToInt32(r.GetAttribute("Offset")); currentVersion.Comments.Add(new Comment() { Anchor = currentVersion.Document.CreateAnchor(offset), Text = text }); } // ColorSegments else if (r.NodeType == XmlNodeType.Element && r.Name == "ColorSegments") { } else if (r.NodeType == XmlNodeType.Element && r.Name == "ColorSegment") { string textColor = r.GetAttribute("Color"); int start = Convert.ToInt32(r.GetAttribute("Start")); int end = Convert.ToInt32(r.GetAttribute("End")); Color? color = ColorConverter.ConvertFromString(textColor) as Color?; SolidColorBrush b = new SolidColorBrush(color.Value); currentVersion.ColorSegments.Add(new ColorSegment() { Color = b, Start = currentVersion.Document.CreateAnchor(start), End = currentVersion.Document.CreateAnchor(end) }); } // Bookmarks else if (r.NodeType == XmlNodeType.Element && r.Name == "Bookmarks") { } else if (r.NodeType == XmlNodeType.Element && r.Name == "Bookmark") { int offset = Convert.ToInt32(r.GetAttribute("Offset")); int key = Convert.ToInt32(r.GetAttribute("Key")); Bookmark bookmark = new Bookmark(_codeFile, currentVersion.Document.CreateAnchor(offset), key, r.GetAttribute("Mark")); currentVersion.Bookmarks.Add(bookmark); } else if (r.NodeType == XmlNodeType.Element && r.Name == "Text") { int hash = Convert.ToInt32(r.GetAttribute("Hash")); string name = r.GetAttribute("Name"); // Загружаем файл по этому имени idx = zf.FindEntry(name, false); ZipEntry entryFile = zf[idx]; StreamReader reader = new StreamReader(zf.GetInputStream(entryFile)); currentVersion.Document.Text = reader.ReadToEnd(); // Сравниваем хеш-код if (currentVersion.Document.Text.GetHashCode() != hash) { throw new FileHashException(_codeFile.Path); } } } } } catch (IOException ex) { throw new LoadCodeFileException(Path, ex); } catch (XmlException ex) { throw new LoadCodeFileException(Path, ex); } catch (XmlSchemaException ex) { throw new LoadCodeFileException(Path, ex); } catch (UnauthorizedAccessException ex) { throw new LoadCodeFileException(Path, ex); } finally { if (zf != null) { zf.IsStreamOwner = true; // Makes close also shut the underlying stream zf.Close(); } } }
/// <summary> /// Initializes encryption keys based on given password. /// </summary> protected void InitializeAESPassword(ZipEntry entry, string rawPassword, out byte[] salt, out byte[] pwdVerifier) { salt = new byte[entry.AESSaltLen]; // Salt needs to be cryptographically random, and unique per file if (_aesRnd == null) _aesRnd = new RNGCryptoServiceProvider(); _aesRnd.GetBytes(salt); int blockSize = entry.AESKeySize / 8; // bits to bytes cryptoTransform_ = new ZipAESTransform(rawPassword, salt, blockSize, true); pwdVerifier = ((ZipAESTransform)cryptoTransform_).PwdVerifier; }
void ExtractEntry(ZipEntry entry) { bool doExtraction = entry.IsCompressionMethodSupported(); string targetName = entry.Name; if ( doExtraction ) { if ( entry.IsFile ) { targetName = extractNameTransform_.TransformFile(targetName); } else if ( entry.IsDirectory ) { targetName = extractNameTransform_.TransformDirectory(targetName); } doExtraction = !((targetName == null) || (targetName.Length == 0)); } // TODO: Fire delegate/throw exception were compression method not supported, or name is invalid? string dirName = null; if ( doExtraction ) { if ( entry.IsDirectory ) { dirName = targetName; } else { dirName = Path.GetDirectoryName(Path.GetFullPath(targetName)); } } if ( doExtraction && !Directory.Exists(dirName) ) { if ( !entry.IsDirectory || CreateEmptyDirectories ) { try { Directory.CreateDirectory(dirName); } catch (Exception ex) { doExtraction = false; if ( events_ != null ) { if ( entry.IsDirectory ) { continueRunning_ = events_.OnDirectoryFailure(targetName, ex); } else { continueRunning_ = events_.OnFileFailure(targetName, ex); } } else { continueRunning_ = false; throw; } } } } if ( doExtraction && entry.IsFile ) { ExtractFileEntry(entry, targetName); } }
/// <summary> /// Creates a new content file representation /// </summary> /// <param name="zipFile">The archive containing the file</param> /// <param name="zipEntry">The actual content file</param> public ContentArchiveEntry(ZipFile zipFile, ZipEntry zipEntry) { ZipFile = zipFile; ZipEntry = zipEntry; }
protected void lBtnDownloadAlbum_Click(object sender, EventArgs e) { MiscellaneousController objMisc = new MiscellaneousController(); string[] getPath = CommonUtilities.GetPath(); StateManager objStateManager = StateManager.Instance; //to get logged in user name from session as user is logged in user objSessionValue = (SessionValue)objStateManager.Get("objSessionvalue", StateManager.State.Session); if (Request.QueryString["PhotoAlbumId"] != null) { if (int.TryParse(Request.QueryString["PhotoAlbumId"], out _photoAlbumId)) { DownloadPhotoAlbumId = _photoAlbumId; Session["PhotoAlbumId"] = _photoAlbumId.ToString(); string imagePath = string.Empty; Tributes objTributes = objTribute = (Tributes)objStateManager.Get(PortalEnums.SessionValueEnum.TributeSession.ToString(), StateManager.State.Session); if (objTributes != null) { if (string.IsNullOrEmpty(objTributes.TributePackageType)) { _packageId = objMisc.GetTributePackageId(_tributeId); } } bool isAllowedPhotoCheck = false; string tributeEndDate = objMisc.GetTributeEndDate(_tributeId); DateTime date2 = new DateTime(); //MG:Expiry Notice DateTime dt = new DateTime(); if (!tributeEndDate.Equals("Never")) { if (tributeEndDate.Contains("/")) { string[] date = tributeEndDate.Split('/'); date2 = new DateTime(int.Parse(date[2]), int.Parse(date[0]), int.Parse(date[1])); } } isAllowedPhotoCheck = objMisc.IsAllowedPhotoCheck(_photoAlbumId); if (((_packageId == 3) || (_packageId == 6) || (_packageId == 7) || (_packageId == 8)) || ((_packageId == 5) && !isAllowedPhotoCheck && (date2 < DateTime.Now))) { #region popup if (Equals(objSessionValue, null))//when not logged in { if (IsCustomHeaderOn) topHeight = 198; else topHeight = 81; } else { if (IsCustomHeaderOn) topHeight = 261; else topHeight = 133; } if (Request.QueryString["PhotoAlbumId"] != null) { if (_photoAlbumId > 0) Session["PhotoAlbumId"] = _photoAlbumId.ToString(); } if (WebConfig.ApplicationMode.Equals("local")) { appDomian = WebConfig.AppBaseDomain.ToString(); } else { StateManager stateManager = StateManager.Instance; Tributes objTrib = (Tributes)stateManager.Get("TributeSession", StateManager.State.Session); appDomian = "http://" + objTrib.TypeDescription.ToString().ToLower().Replace("new baby", "newbaby") + "." + WebConfig.TopLevelDomain + "/"; } ScriptManager.RegisterStartupScript(Page, this.GetType(), "awe", "fnReachLimitExpiryPopup('location.href','document.title','UpgradeAlbum','" + _tributeUrl + "','" + _tributeId + "','" + appDomian + "','" + topHeight + "');", true); #endregion } else { #region allowFunctionality List<Photos> objListPhotos = new List<Photos>(); Photos objPhotos = new Photos(); if (Request.QueryString["PhotoAlbumId"] != null) { int.TryParse(Request.QueryString["PhotoAlbumId"], out DownloadPhotoAlbumId); objPhotos.PhotoAlbumId = DownloadPhotoAlbumId; } objListPhotos = objMisc.GetPhotoImagesList(objPhotos); if ((DownloadPhotoAlbumId > 0) && (objListPhotos.Count > 0)) { // zip up the files try { string sTargetFolderPath = getPath[0] + "/" + getPath[1] + "/" + _tributeUrl.Replace(" ", "_") + "_" + _tributeType.Replace(" ", "_"); //to create directory for image. string galleryPath = getPath[0] + "/" + getPath[1] + "/" + getPath[6]; string sZipFileName = "Album_" + DownloadPhotoAlbumId.ToString(); string[] filenames = Directory.GetFiles(sTargetFolderPath); // Zip up the files - From SharpZipLib Demo Code using (ZipOutputStream s = new ZipOutputStream(File.Create(galleryPath + "\\" + sZipFileName + ".zip"))) { s.SetLevel(9); // 0-9, 9 being the highest level of compression byte[] buffer = new byte[4096]; foreach (Photos objPhoto in objListPhotos) { bool Foundflag = true; string ImageFile = string.Empty; string smallFile = string.Empty; ImageFile = sTargetFolderPath + "\\" + "/Big_" + objPhoto.PhotoImage; smallFile = sTargetFolderPath + "\\" + objPhoto.PhotoImage; foreach (string file in filenames) { if ((file.EndsWith("Big_" + objPhoto.PhotoImage)) && (File.Exists(ImageFile))) { Foundflag = false; //FlagsAttribute set false for small image //Code to zip ZipEntry entry = new ZipEntry(Path.GetFileName(ImageFile)); entry.DateTime = DateTime.Now; s.PutNextEntry(entry); using (FileStream fs = File.OpenRead(ImageFile)) { int sourceBytes; do { sourceBytes = fs.Read(buffer, 0, buffer.Length); s.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } //Code to zip till here } } if (Foundflag) // if big image is not found. { foreach (string file in filenames) { if ((file.EndsWith(objPhoto.PhotoImage)) && (File.Exists(smallFile)) && (!(file.EndsWith("Big_" + objPhoto.PhotoImage)))) //(File.Exists(smallFile)) { ZipEntry entry = new ZipEntry(Path.GetFileName(file)); entry.DateTime = DateTime.Now; s.PutNextEntry(entry); using (FileStream fs = File.OpenRead(file)) { int sourceBytes; do { sourceBytes = fs.Read(buffer, 0, buffer.Length); s.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } } } } } s.Finish(); s.Close(); } Response.ContentType = "zip"; string sfile = sZipFileName + ".zip"; Response.AppendHeader("Content-Disposition", "attachment; filename=" + sfile); Response.TransmitFile(galleryPath + "\\" + sfile); Response.End(); } catch //Exception ex) // by Ud { } } #endregion } } } }
public void OnPostUnzip(ZipEntry _entry) { //Debug.Log(_entry.Name); }
/// <summary> /// Adds the file specified in <paramref name="filePath"/> to the ZIP archive. If <paramref name="fileNameForZip"/> /// is specified, use that filename as the name of the file in the ZIP archive. /// </summary> /// <param name="zos">The ZipOutputStream (ZIP archive) the media object file is to be added to.</param> /// <param name="filePath">The full path to the media object file to be added to the ZIP archive. /// Ex: C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\desert sunsets\zOpt_sonorandesert.jpg</param> /// <param name="fileNameForZip">The full path to the file whose name is to be used to name the file specified /// by <paramref name="filePath"/> in the ZIP archive. If null or empty, the actual filename is used. This path /// does not have to refer to an existing file on disk, but it must begin with <paramref name="basePath"/>. /// Ex: C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\desert sunsets\sonorandesert.jpg</param> /// <param name="basePath">The full path to the directory containing the highest-level media file to be added /// to the ZIP archive. Must include trailing slash. Ex: C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\</param> /// <param name="isImage">Indicates whether the file specified in <paramref name="filePath"/> is an image. If it /// is, and <paramref name="applyWatermark"/> is <c>true</c>, a watermark is applied to the image as it is inserted /// into the archive.</param> /// <param name="applyWatermark">Indicates whether to apply a watermark to images as they are added to the archive. /// Applies only when <paramref name="isImage"/> is <c>true</c>.</param> private static void AddFileZipEntry(ZipOutputStream zos, string filePath, string fileNameForZip, string basePath, bool isImage, bool applyWatermark) { int bufferSize = Configuration.ConfigManager.GetGalleryServerProConfigSection().Core.MediaObjectDownloadBufferSize; byte[] buffer = new byte[bufferSize]; #region Determine ZIP entry name // Get name of the file as it will be stored in the ZIP archive. This is the fragment of the full file path // after the base path. Ex: If basePath="C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\" // and filePath="C:\Inetpub\wwwroot\galleryserverpro\mediaobjects\Summer 2005\sunsets\desert sunsets\zOpt_sonorandesert.jpg", // then zipEntryName="desert sunsets\zOpt_sonorandesert.jpg". The ZIP algorithm will automatically sense the // embedded directory ("desert sunsets") and create it. string zipEntryName; if (String.IsNullOrEmpty(fileNameForZip)) { zipEntryName = filePath.Replace(basePath, String.Empty); } else { zipEntryName = fileNameForZip.Replace(basePath, String.Empty); } #endregion using (Stream stream = CreateStream(filePath, isImage, applyWatermark)) { ZipEntry entry = new ZipEntry(zipEntryName); entry.Size = stream.Length; zos.PutNextEntry(entry); int byteCount; while ((byteCount = stream.Read(buffer, 0, buffer.Length)) > 0) { zos.Write(buffer, 0, byteCount); } } }
public void OnPostZip(ZipEntry _entry) { }
private bool Evaluate(ZipEntry entry) { bool result = _Criterion.Evaluate(entry); return result; }
public bool OnPreUnzip(ZipEntry _entry) { return(true); }
internal override bool Evaluate(ZipEntry entry) { DateTime x; switch (Which) { case WhichTime.atime: x = entry.AccessedTime; break; case WhichTime.mtime: x = entry.ModifiedTime; break; case WhichTime.ctime: x = entry.CreationTime; break; default: throw new ArgumentException("??time"); } return _Evaluate(x); }
private bool extractUpdate() { if (File.Exists("update.zip")) { log.Enqueue(new LogEntry("Unpacking update...")); try { ZipFile update_file = new ZipFile("update.zip"); log.Enqueue(new LogEntry(update_file.Count + " files detected.")); for (int i = 0; i < update_file.Count; i++) { float percentage = ((float)i / (float)update_file.Count); ZipEntry fileentry = update_file[i]; log.Enqueue(new LogEntry("[" + Math.Truncate(percentage * 100) + "%] Updating: " + fileentry.FileName)); this.extractprogess = (float)(Math.Truncate(percentage * 100) / 100.0f); if (ignorefiles.Contains(fileentry.FileName)) { continue; } try { if (File.Exists(fileentry.FileName)) { File.Move(fileentry.FileName, fileentry.FileName + ".updateremove"); } fileentry.Extract(); } catch (IOException e) { log.Enqueue(new LogEntry(fileentry.FileName + " is inaccessible.", Color.Red)); MessageBox.Show(fileentry.FileName + " is inaccessible.\r\nPlease close Aurora.\r\n\r\n" + e.Message); i--; continue; } } update_file.Dispose(); File.Delete("update.zip"); } catch (Exception exc) { log.Enqueue(new LogEntry(exc.Message, Color.Red)); return(false); } log.Enqueue(new LogEntry("All files updated.")); log.Enqueue(new LogEntry()); log.Enqueue(new LogEntry("You can now close the updater and restart Aurora.")); this.extractprogess = 1.0f; return(true); } else { this.log.Enqueue(new LogEntry("Update file not found.", Color.Red)); return(false); } }
void ProcessZipEntry(string filename, byte[] data, ZipEntry entry) { }
public static string GetFileName(ZipEntry entry) { return(Argument.NotNull(entry, nameof(entry)).FileName.Split(PathSplit, StringSplitOptions.RemoveEmptyEntries).Last()); }
private void AddFile([NotNull] ZipEntry entry) { Files.Add(entry); }
/// <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(); } }
/// <summary> /// 解压文件到指定文件夹 /// </summary> /// <param name="sourceFile">压缩文件</param> /// <param name="destinationDirectory">目标文件夹,如果为空则解压到当前文件夹下</param> /// <param name="password">密码</param> /// <returns></returns> public static bool DecomparessFile(string sourceFile, string destinationDirectory = null, string password = null) { bool result = false; if (!File.Exists(sourceFile)) { throw new FileNotFoundException("要解压的文件不存在", sourceFile); } if (string.IsNullOrWhiteSpace(destinationDirectory)) { destinationDirectory = Path.GetDirectoryName(sourceFile); } try { if (!Directory.Exists(destinationDirectory)) { Directory.CreateDirectory(destinationDirectory); } using (ZipInputStream zipStream = new ZipInputStream(File.Open(sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read))) { zipStream.Password = password; ZipEntry zipEntry = zipStream.GetNextEntry(); while (zipEntry != null) { if (zipEntry.IsDirectory)//如果是文件夹则创建 { Directory.CreateDirectory(Path.Combine(destinationDirectory, Path.GetDirectoryName(zipEntry.Name))); } else { string fileName = Path.GetFileName(zipEntry.Name); if (!string.IsNullOrEmpty(fileName) && fileName.Trim().Length > 0) { FileInfo fileItem = new FileInfo(Path.Combine(destinationDirectory, zipEntry.Name.Split('/').Last())); zipEntry.Name.Split('/').Last(); using (FileStream writeStream = fileItem.Create()) { byte[] buffer = new byte[4096]; int readLength = 0; do { readLength = zipStream.Read(buffer, 0, 4096); writeStream.Write(buffer, 0, readLength); } while (readLength == 4096); writeStream.Flush(); writeStream.Close(); } fileItem.LastWriteTime = zipEntry.DateTime; } } zipEntry = zipStream.GetNextEntry();//获取下一个文件 } zipStream.Close(); } result = true; } catch (System.Exception ex) { throw new Exception("文件解压发生错误", ex); } return(result); }
static IEnumerator DoLoad(string name, int?seed = null) { var api = ApiManager.Instance; using (var db = Database.DatabaseManager.Open()) { var sql = Sql.Builder.From("maps").Where("name = @0", name); var map = db.FirstOrDefault <Database.MapModel>(sql); if (map == null) { api.SendError($"Environment '{name}' is not available"); yield break; } AssetBundle textureBundle = null; AssetBundle mapBundle = null; ZipFile zip = new ZipFile(map.LocalPath); try { Manifest manifest; ZipEntry entry = zip.GetEntry("manifest"); using (var ms = zip.GetInputStream(entry)) { int streamSize = (int)entry.Size; byte[] buffer = new byte[streamSize]; streamSize = ms.Read(buffer, 0, streamSize); manifest = new Deserializer().Deserialize <Manifest>(Encoding.UTF8.GetString(buffer)); } if (manifest.bundleFormat != BundleConfig.MapBundleFormatVersion) { api.SendError("Out of date Map AssetBundle. Please check content website for updated bundle or rebuild the bundle."); yield break; } var texStream = zip.GetInputStream(zip.GetEntry($"{manifest.bundleGuid}_environment_textures")); textureBundle = AssetBundle.LoadFromStream(texStream, 0, 1 << 20); string platform = SystemInfo.operatingSystemFamily == OperatingSystemFamily.Windows ? "windows" : "linux"; var mapStream = zip.GetInputStream(zip.GetEntry($"{manifest.bundleGuid}_environment_main_{platform}")); mapBundle = AssetBundle.LoadFromStream(mapStream, 0, 1 << 20); if (mapBundle == null || textureBundle == null) { api.SendError($"Failed to load environment from '{map.Name}' asset bundle"); yield break; } textureBundle.LoadAllAssets(); var scenes = mapBundle.GetAllScenePaths(); if (scenes.Length != 1) { api.SendError($"Unsupported environment in '{map.Name}' asset bundle, only 1 scene expected"); yield break; } var sceneName = Path.GetFileNameWithoutExtension(scenes[0]); var loader = SceneManager.LoadSceneAsync(sceneName); yield return(new WaitUntil(() => loader.isDone)); SIM.LogAPI(SIM.API.SimulationLoad, sceneName); var sim = UnityEngine.Object.Instantiate(Loader.Instance.SimulatorManagerPrefab); sim.name = "SimulatorManager"; sim.Init(seed); } finally { textureBundle?.Unload(false); mapBundle?.Unload(false); zip.Close(); } // TODO deactivate environment props if needed api.Reset(); api.CurrentScene = name; api.SendResult(); } }
void ExtractFileEntry(ZipEntry entry, string targetName) { bool proceed = true; if ( overwrite_ != Overwrite.Always ) { if ( File.Exists(targetName) ) { if ( (overwrite_ == Overwrite.Prompt) && (confirmDelegate_ != null) ) { proceed = confirmDelegate_(targetName); } else { proceed = false; } } } if ( proceed ) { if ( events_ != null ) { continueRunning_ = events_.OnProcessFile(entry.Name); } if ( continueRunning_ ) { try { using ( FileStream outputStream = File.Create(targetName) ) { if ( buffer_ == null ) { buffer_ = new byte[4096]; } if ((events_ != null) && (events_.Progress != null)) { StreamUtils.Copy(zipFile_.GetInputStream(entry), outputStream, buffer_, events_.Progress, events_.ProgressInterval, this, entry.Name, entry.Size); } else { StreamUtils.Copy(zipFile_.GetInputStream(entry), outputStream, buffer_); } if (events_ != null) { continueRunning_ = events_.OnCompletedFile(entry.Name); } } #if !NETCF_1_0 && !NETCF_2_0 if ( restoreDateTimeOnExtract_ ) { File.SetLastWriteTime(targetName, entry.DateTime); } if ( RestoreAttributesOnExtract && entry.IsDOSEntry && (entry.ExternalFileAttributes != -1)) { FileAttributes fileAttributes = (FileAttributes) entry.ExternalFileAttributes; // TODO: FastZip - Setting of other file attributes on extraction is a little trickier. fileAttributes &= (FileAttributes.Archive | FileAttributes.Normal | FileAttributes.ReadOnly | FileAttributes.Hidden); File.SetAttributes(targetName, fileAttributes); } #endif } catch(Exception ex) { if ( events_ != null ) { continueRunning_ = events_.OnFileFailure(targetName, ex); } else { continueRunning_ = false; throw; } } } } }
/// <summary> /// 带压缩流压缩单个文件 /// </summary> /// <param name="fileToZip">要进行压缩的文件名</param> /// <param name="zipStream"></param> /// <returns></returns> private static bool ZipFileWithStream(string fileToZip, ZipOutputStream zipStream) { //如果文件没有找到,则报错 //if (!File.Exists(fileToZip)) //{ // throw new FileNotFoundException("指定要压缩的文件: " + fileToZip + " 不存在!"); //} //FileStream fs = null; FileStream zipFile = null; ZipEntry zipEntry = null; Crc32 crc = new Crc32(); bool res = true; try { if (fileToZip.IndexOf("*") > -1) { var files = _getFileByPath(fileToZip); if (files != null && files.Count > 0) { foreach (string file in files) { //打开压缩文件 zipFile = File.OpenRead(file); byte[] buffer = new byte[zipFile.Length]; zipFile.Read(buffer, 0, buffer.Length); zipEntry = new ZipEntry(file); zipEntry.DateTime = DateTime.Now; zipEntry.Size = zipFile.Length; zipFile.Close(); crc.Reset(); crc.Update(buffer); zipEntry.Crc = crc.Value; zipStream.PutNextEntry(zipEntry); zipStream.Write(buffer, 0, buffer.Length); } } } else { zipFile = File.OpenRead(fileToZip); byte[] buffer = new byte[zipFile.Length]; zipFile.Read(buffer, 0, buffer.Length); zipFile.Close(); zipEntry = new ZipEntry(fileToZip); zipStream.PutNextEntry(zipEntry); zipStream.Write(buffer, 0, buffer.Length); } } catch (Exception ex) { res = false; } finally { if (zipEntry != null) { } if (zipFile != null) { zipFile.Close(); } GC.Collect(); GC.Collect(1); } return(res); }
/// <summary> /// 压缩文件夹的方法 /// </summary> /// <param name="DirToZip">被压缩的文件名称(包含文件路径)</param> /// <param name="ZipedFile">压缩后的文件名称(包含文件路径)</param> /// <param name="CompressionLevel">压缩率0(无压缩),9(压缩率最高)</param> public void ZipDir(string DirToZip, string ZipedFile, int CompressionLevel) { //压缩文件为空时默认与压缩文件夹同一级目录 if (ZipedFile == string.Empty) { ZipedFile = DirToZip.Substring(DirToZip.LastIndexOf("/") + 1); ZipedFile = DirToZip.Substring(0, DirToZip.LastIndexOf("/")) + "//" + ZipedFile + ".zip"; } if (Path.GetExtension(ZipedFile) != ".zip") { ZipedFile = ZipedFile + ".zip"; } using (ZipOutputStream zipoutputstream = new ZipOutputStream(File.Create(ZipedFile))) { zipoutputstream.SetLevel(CompressionLevel); Crc32 crc = new Crc32(); Hashtable fileList = getAllFies(DirToZip); foreach (DictionaryEntry item in fileList) { FileStream fs = File.OpenRead(item.Key.ToString()); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); ZipEntry entry = new ZipEntry(item.Key.ToString().Substring(DirToZip.Length)); entry.DateTime = (DateTime)item.Value; entry.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; zipoutputstream.PutNextEntry(entry); zipoutputstream.Write(buffer, 0, buffer.Length); } } }
private void BindGrid(string installPath, DataGrid grid) { var packages = new List <PackageInfo>(); var invalidPackages = new List <string>(); foreach (string file in Directory.GetFiles(installPath)) { if (file.ToLower().EndsWith(".zip") || file.ToLower().EndsWith(".resources")) { Stream inputStream = new FileStream(file, FileMode.Open, FileAccess.Read); var unzip = new ZipInputStream(inputStream); try { ZipEntry entry = unzip.GetNextEntry(); while (entry != null) { if (!entry.IsDirectory) { var fileName = entry.Name; string extension = System.IO.Path.GetExtension(fileName); if (extension.ToLower() == ".dnn" || extension.ToLower() == ".dnn5") { //Manifest var manifestReader = new StreamReader(unzip); var manifest = manifestReader.ReadToEnd(); var package = new PackageInfo(); package.Manifest = manifest; if (!string.IsNullOrEmpty(manifest)) { var doc = new XPathDocument(new StringReader(manifest)); XPathNavigator rootNav = doc.CreateNavigator().SelectSingleNode("dotnetnuke"); string packageType = String.Empty; if (rootNav.Name == "dotnetnuke") { packageType = XmlUtils.GetAttributeValue(rootNav, "type"); } else if (rootNav.Name.ToLower() == "languagepack") { packageType = "LanguagePack"; } XPathNavigator nav = null; switch (packageType.ToLower()) { case "package": nav = rootNav.SelectSingleNode("packages/package"); break; case "module": case "languagepack": case "skinobject": nav = Installer.ConvertLegacyNavigator(rootNav, new InstallerInfo()).SelectSingleNode("packages/package"); break; } if (nav != null) { package.Name = XmlUtils.GetAttributeValue(nav, "name"); package.PackageType = XmlUtils.GetAttributeValue(nav, "type"); package.IsSystemPackage = XmlUtils.GetAttributeValueAsBoolean(nav, "isSystem", false); package.Version = new Version(XmlUtils.GetAttributeValue(nav, "version")); package.FriendlyName = XmlUtils.GetNodeValue(nav, "friendlyName"); if (String.IsNullOrEmpty(package.FriendlyName)) { package.FriendlyName = package.Name; } package.Description = XmlUtils.GetNodeValue(nav, "description"); package.FileName = file.Replace(installPath + "\\", ""); XPathNavigator foldernameNav = null; switch (package.PackageType) { case "Module": case "Auth_System": foldernameNav = nav.SelectSingleNode("components/component/files"); if (foldernameNav != null) { package.FolderName = Util.ReadElement(foldernameNav, "basePath").Replace('\\', '/'); } break; case "Container": foldernameNav = nav.SelectSingleNode("components/component/containerFiles"); if (foldernameNav != null) { package.FolderName = Globals.glbContainersPath + Util.ReadElement(foldernameNav, "containerName").Replace('\\', '/'); } break; case "Skin": foldernameNav = nav.SelectSingleNode("components/component/skinFiles"); if (foldernameNav != null) { package.FolderName = Globals.glbSkinsPath + Util.ReadElement(foldernameNav, "skinName").Replace('\\', '/'); } break; default: break; } XPathNavigator iconFileNav = nav.SelectSingleNode("iconFile"); if (package.FolderName != string.Empty && iconFileNav != null) { if ((iconFileNav.Value != string.Empty) && (package.PackageType == "Module" || package.PackageType == "Auth_System" || package.PackageType == "Container" || package.PackageType == "Skin")) { package.IconFile = package.FolderName + "/" + iconFileNav.Value; package.IconFile = (!package.IconFile.StartsWith("~/")) ? "~/" + package.IconFile : package.IconFile; } } packages.Add(package); } } break; } } entry = unzip.GetNextEntry(); } } catch (Exception) { invalidPackages.Add(file); } finally { unzip.Close(); unzip.Dispose(); } } } if (invalidPackages.Count > 0) { var pkgErrorsMsg = invalidPackages.Aggregate(string.Empty, (current, pkg) => current + (pkg + "<br />")); UI.Skins.Skin.AddModuleMessage(this, Localization.GetString("PackageErrors.Text", LocalResourceFile) + pkgErrorsMsg, ModuleMessage.ModuleMessageType.RedError); } grid.DataSource = packages; grid.DataBind(); }
public static void ZipAndroidResources() { try { var filenames = GatherAndroidResourceFiles(); // 'using' statements guarantee the stream is closed properly which is a big source // of problems otherwise. Its exception safe as well which is great. using (ZipOutputStream zipStream = new ZipOutputStream(File.Create(Application.dataPath + "/Android.zip"))) { zipStream.SetLevel(9); // 0 - store only to 9 - means best compression byte[] buffer = new byte[4096]; foreach (string file in filenames) { string name = file.Substring(AndroidResourceFolder.Length + 1); ZipEntry entry = new ZipEntry(name); // Setup the entry data as required. // Crc and size are handled by the library for seakable streams // so no need to do them here. // Could also use the last write time or similar for the file. entry.DateTime = System.DateTime.Now; zipStream.PutNextEntry(entry); using (FileStream fileStream = File.OpenRead(file)) { // Using a fixed size buffer here makes no noticeable difference for output // but keeps a lid on memory usage. int sourceBytes; do { sourceBytes = fileStream.Read(buffer, 0, buffer.Length); zipStream.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } } // Finish/Close arent needed strictly as the using statement does this automatically // Finish is important to ensure trailing information for a Zip file is appended. Without this // the created file would be invalid. zipStream.Finish(); // Close is important to wrap things up and unlock the file. zipStream.Close(); AssetDatabase.Refresh(); } } catch (Exception ex) { Debug.LogError(string.Format("Exception during processing {0}", ex)); // No need to rethrow the exception as for our purposes its handled. } }
/// <summary> /// Read data direct from drive to file /// </summary> /// <param name="driveLetter"></param> /// <param name="fileName"></param> /// <param name="eCompType"></param> /// <returns></returns> public bool ReadDrive(string driveLetter, string fileName, EnumCompressionType eCompType, bool bUseMBR) { IsCancelling = false; var dtStart = DateTime.Now; // // Map to physical drive // var physicalDrive = _diskAccess.GetPhysicalPathForLogicalPath(driveLetter); if (string.IsNullOrEmpty(physicalDrive)) { LogMsg(Resources.Disk_WriteDrive_Error__Couldn_t_map_partition_to_physical_drive); _diskAccess.UnlockDrive(); return(false); } // // Lock logical drive // var success = _diskAccess.LockDrive(driveLetter); if (!success) { LogMsg(Resources.Disk_WriteDrive_Failed_to_lock_drive); return(false); } // // Get drive size // var driveSize = _diskAccess.GetDriveSize(physicalDrive); if (driveSize <= 0) { LogMsg(Resources.Disk_WriteDrive_Failed_to_get_device_size); _diskAccess.UnlockDrive(); return(false); } var readSize = driveSize; // // Open the physical drive // var physicalHandle = _diskAccess.Open(physicalDrive); if (physicalHandle == null) { LogMsg(Resources.Disk_WriteDrive_Failed_to_open_physical_drive); _diskAccess.UnlockDrive(); return(false); } // // Start doing the read // var buffer = new byte[Globals.MaxBufferSize]; var offset = 0L; using (var basefs = (Stream) new FileStream(fileName, FileMode.Create, FileAccess.Write)) { Stream fs; switch (eCompType) { case EnumCompressionType.Zip: var zfs = new ZipOutputStream(basefs); // Default to middle of the range compression zfs.SetLevel(Globals.CompressionLevel); var fi = new FileInfo(fileName); var entryName = fi.Name; entryName = entryName.ToLower().Replace(".zip", ""); entryName = ZipEntry.CleanName(entryName); var zipEntry = new ZipEntry(entryName) { DateTime = fi.LastWriteTime }; zfs.IsStreamOwner = true; // Todo: Consider whether size needs setting for older utils ? zfs.PutNextEntry(zipEntry); fs = zfs; break; case EnumCompressionType.Gzip: var gzis = new GZipOutputStream(basefs); gzis.SetLevel(Globals.CompressionLevel); gzis.IsStreamOwner = true; fs = gzis; break; case EnumCompressionType.Targzip: var gzos = new GZipOutputStream(basefs); gzos.SetLevel(Globals.CompressionLevel); gzos.IsStreamOwner = true; var tos = new TarOutputStream(gzos); fs = tos; break; case EnumCompressionType.XZ: var xzs = new XZOutputStream(basefs); fs = xzs; break; default: // No compression - direct to file stream fs = basefs; break; } while (offset < readSize && !IsCancelling) { // NOTE: If we provide a buffer that extends past the end of the physical device ReadFile() doesn't // seem to do a partial read. Deal with this by reading the remaining bytes at the end of the // drive if necessary var readMaxLength = (int) ((((ulong)readSize - (ulong)offset) < (ulong)buffer.Length) ? ((ulong)readSize - (ulong)offset) : (ulong)buffer.Length); int readBytes; if (_diskAccess.Read(buffer, readMaxLength, out readBytes) < 0) { LogMsg(Resources.Disk_ReadDrive_Error_reading_data_from_drive__ + Marshal.GetHRForLastWin32Error()); goto readfail1; } if (readBytes == 0) { LogMsg(Resources.Disk_ReadDrive_Error_reading_data_from_drive___past_EOF_); goto readfail1; } // Check MBR if (bUseMBR && offset == 0) { var truncatedSize = ParseMBRForSize(buffer); if (truncatedSize > driveSize) { LogMsg(Resources.Disk_ReadDrive_Problem_with_filesystem__It_reports_it_is_larger_than_the_disk_); goto readfail1; } if (truncatedSize == 0) { LogMsg(Resources.Disk_ReadDrive_No_valid_partitions_on_drive); goto readfail1; } readSize = truncatedSize; } if (offset == 0) { switch (eCompType) { case EnumCompressionType.Targzip: var fi = new FileInfo(fileName); var entryName = fi.Name; entryName = entryName.ToLower().Replace(".tar.gz", ""); entryName = entryName.ToLower().Replace(".tgz", ""); var tarEntry = TarEntry.CreateTarEntry(entryName); tarEntry.Size = readSize; tarEntry.ModTime = DateTime.SpecifyKind(fi.LastWriteTime, DateTimeKind.Utc); ((TarOutputStream)fs).PutNextEntry(tarEntry); break; } } fs.Write(buffer, 0, readBytes); offset += (uint)readBytes; var percentDone = (int)(100 * offset / readSize); var tsElapsed = DateTime.Now.Subtract(dtStart); var bytesPerSec = offset / tsElapsed.TotalSeconds; Progress(percentDone); LogMsg(Resources.Disk_ReadDrive_Read + @": " + (offset / Globals.MbModifier) + @" / " + (readSize / Globals.MbModifier) + @" MB " + @"(" + Resources.Disk_ReadDrive_Physical + @": " + (driveSize / Globals.MbModifier) + " MB); " + string.Format("{0:F}", (bytesPerSec / Globals.MbModifier)) + @" MB/s; " + Resources.Disk_Elapsed_time + ": " + tsElapsed.ToString(@"hh\:mm\:ss")); } if (fs is ZipOutputStream) { ((ZipOutputStream)fs).CloseEntry(); ((ZipOutputStream)fs).Close(); } else if (fs is TarOutputStream) { ((TarOutputStream)fs).CloseEntry(); fs.Close(); } else if (fs is GZipOutputStream) { fs.Close(); } else if (fs is XZOutputStream) { fs.Close(); } } readfail1: _diskAccess.Close(); _diskAccess.UnlockDrive(); var tstotalTime = DateTime.Now.Subtract(dtStart); if (IsCancelling) { LogMsg(Resources.Disk_WriteDrive_Cancelled); } else { LogMsg(Resources.Disk_ReadDrive_All_Done_Read + @" " + offset + @" " + Resources.Disk_WriteDrive_bytes + @". " + Resources.Disk_Elapsed_time + @": " + tstotalTime.ToString(@"hh\:mm\:ss")); } Progress(0); return(true); }
protected string CreateBackup() { var Url = Request.Url; string zipFilename = Url.Scheme + "_" + Url.Host + (Url.IsDefaultPort ? "" : (" " + Url.Port)) + "_" + DateTime.Now.ToString("yyyy_MM.dd_HHmm") + ".zip"; string zipFilePath = PathCombine(BackupDirectory, zipFilename); if (!C1Directory.Exists(Path.GetDirectoryName(zipFilePath))) C1Directory.CreateDirectory(Path.GetDirectoryName(zipFilePath)); #region Zipping var filenames = GetFilesRecursive(BaseDirectory); var directories = GetDirectoriesRecursive(BaseDirectory); using (ZipOutputStream s = new ZipOutputStream(FileCreate(zipFilePath))) { lock (_lock) { int oldScriptTimeOut = Server.ScriptTimeout; Server.ScriptTimeout = 600; // 10 minutes s.SetLevel(1); // 0 - store only to 9 - means best compression byte[] buffer = new byte[4096]; foreach (string directory in directories) { if (directory.Contains(backupDirectoryRelativePath)) continue; ZipEntry entry = new ZipEntry(directory.Replace(BaseDirectory, "").Replace("\\", "/") + "/"); entry.DateTime = DateTime.Now; s.PutNextEntry(entry); s.CloseEntry(); } foreach (string file in filenames) { if (file.Contains(backupDirectoryRelativePath) || IsTemporaryDirectory(file)) continue; ZipEntry entry = new ZipEntry(file.Replace(BaseDirectory, "").Replace("\\", "/")); try { var fi = new C1FileInfo(file); entry.DateTime = fi.LastWriteTime; entry.Size = fi.Length; using (C1FileStream fs = C1File.OpenRead(file)) { s.PutNextEntry(entry); int sourceBytes; do { sourceBytes = fs.Read(buffer, 0, buffer.Length); s.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } } catch (Exception e) { if (!file.Contains("App_Data\\Composite\\LogFiles")) { this.Validators.Add(new ErrorSummary(e.Message)); } } } Server.ScriptTimeout = oldScriptTimeOut; } s.Finish(); s.Close(); } #endregion return zipFilename; }
private static void WriteClass(TypeWrapper tw) { string name = tw.Name.Replace('.', '/'); string super = null; if (tw.IsInterface) { super = "java/lang/Object"; } else if (tw.BaseTypeWrapper != null) { super = tw.BaseTypeWrapper.Name.Replace('.', '/'); } IKVM.StubGen.ClassFileWriter writer = new IKVM.StubGen.ClassFileWriter(tw.Modifiers, name, super, 0, 49); foreach (TypeWrapper iface in tw.Interfaces) { if (iface.IsPublic || includeNonPublicInterfaces) { writer.AddInterface(iface.Name.Replace('.', '/')); } } IKVM.StubGen.InnerClassesAttribute innerClassesAttribute = null; if (tw.DeclaringTypeWrapper != null) { TypeWrapper outer = tw.DeclaringTypeWrapper; string innername = name; int idx = name.LastIndexOf('$'); if (idx >= 0) { innername = innername.Substring(idx + 1); } innerClassesAttribute = new IKVM.StubGen.InnerClassesAttribute(writer); innerClassesAttribute.Add(name, outer.Name.Replace('.', '/'), innername, (ushort)tw.ReflectiveModifiers); } foreach (TypeWrapper inner in tw.InnerClasses) { if (inner.IsPublic) { if (innerClassesAttribute == null) { innerClassesAttribute = new IKVM.StubGen.InnerClassesAttribute(writer); } string namePart = inner.Name; namePart = namePart.Substring(namePart.LastIndexOf('$') + 1); innerClassesAttribute.Add(inner.Name.Replace('.', '/'), name, namePart, (ushort)inner.ReflectiveModifiers); } } if (innerClassesAttribute != null) { writer.AddAttribute(innerClassesAttribute); } string genericTypeSignature = tw.GetGenericSignature(); if (genericTypeSignature != null) { writer.AddStringAttribute("Signature", genericTypeSignature); } writer.AddStringAttribute("IKVM.NET.Assembly", GetAssemblyName(tw)); if (tw.TypeAsBaseType.IsDefined(StaticCompiler.Universe.Import(typeof(ObsoleteAttribute)), false)) { writer.AddAttribute(new IKVM.StubGen.DeprecatedAttribute(writer)); } foreach (MethodWrapper mw in tw.GetMethods()) { if (!mw.IsHideFromReflection && (mw.IsPublic || mw.IsProtected || includeNonPublicMembers)) { IKVM.StubGen.FieldOrMethod m; if (mw.Name == "<init>") { m = writer.AddMethod(mw.Modifiers, mw.Name, mw.Signature.Replace('.', '/')); IKVM.StubGen.CodeAttribute code = new IKVM.StubGen.CodeAttribute(writer); code.MaxLocals = (ushort)(mw.GetParameters().Length * 2 + 1); code.MaxStack = 3; ushort index1 = writer.AddClass("java/lang/UnsatisfiedLinkError"); ushort index2 = writer.AddString("ikvmstub generated stubs can only be used on IKVM.NET"); ushort index3 = writer.AddMethodRef("java/lang/UnsatisfiedLinkError", "<init>", "(Ljava/lang/String;)V"); code.ByteCode = new byte[] { 187, (byte)(index1 >> 8), (byte)index1, // new java/lang/UnsatisfiedLinkError 89, // dup 19, (byte)(index2 >> 8), (byte)index2, // ldc_w "..." 183, (byte)(index3 >> 8), (byte)index3, // invokespecial java/lang/UnsatisfiedLinkError/init()V 191 // athrow }; m.AddAttribute(code); } else { Modifiers mods = mw.Modifiers; if ((mods & Modifiers.Abstract) == 0) { mods |= Modifiers.Native; } m = writer.AddMethod(mods, mw.Name, mw.Signature.Replace('.', '/')); if (mw.IsOptionalAttributeAnnotationValue) { m.AddAttribute(new IKVM.StubGen.AnnotationDefaultClassFileAttribute(writer, GetAnnotationDefault(writer, mw.ReturnType))); } } MethodBase mb = mw.GetMethod(); if (mb != null) { ThrowsAttribute throws = AttributeHelper.GetThrows(mb); if (throws == null) { string[] throwsArray = mw.GetDeclaredExceptions(); if (throwsArray != null && throwsArray.Length > 0) { IKVM.StubGen.ExceptionsAttribute attrib = new IKVM.StubGen.ExceptionsAttribute(writer); foreach (string ex in throwsArray) { attrib.Add(ex.Replace('.', '/')); } m.AddAttribute(attrib); } } else { IKVM.StubGen.ExceptionsAttribute attrib = new IKVM.StubGen.ExceptionsAttribute(writer); if (throws.classes != null) { foreach (string ex in throws.classes) { attrib.Add(ex.Replace('.', '/')); } } if (throws.types != null) { foreach (Type ex in throws.types) { attrib.Add(ClassLoaderWrapper.GetWrapperFromType(ex).Name.Replace('.', '/')); } } m.AddAttribute(attrib); } if (mb.IsDefined(StaticCompiler.Universe.Import(typeof(ObsoleteAttribute)), false) // HACK the instancehelper methods are marked as Obsolete (to direct people toward the ikvm.extensions methods instead) // but in the Java world most of them are not deprecated (and to keep the Japi results clean we need to reflect this) && (!mb.Name.StartsWith("instancehelper_") || mb.DeclaringType.FullName != "java.lang.String" // the Java deprecated methods actually have two Obsolete attributes || mb.__GetCustomAttributes(StaticCompiler.Universe.Import(typeof(ObsoleteAttribute)), false).Count == 2)) { m.AddAttribute(new IKVM.StubGen.DeprecatedAttribute(writer)); } IList <CustomAttributeData> attr = CustomAttributeData.__GetCustomAttributes(mb, JVM.LoadType(typeof(AnnotationDefaultAttribute)), false); if (attr.Count == 1) { m.AddAttribute(new IKVM.StubGen.AnnotationDefaultClassFileAttribute(writer, GetAnnotationDefault(writer, attr[0].ConstructorArguments[0]))); } } string sig = tw.GetGenericMethodSignature(mw); if (sig != null) { m.AddAttribute(writer.MakeStringAttribute("Signature", sig)); } } } bool hasSerialVersionUID = false; foreach (FieldWrapper fw in tw.GetFields()) { if (!fw.IsHideFromReflection) { bool isSerialVersionUID = includeSerialVersionUID && fw.Name == "serialVersionUID" && fw.FieldTypeWrapper == PrimitiveTypeWrapper.LONG; hasSerialVersionUID |= isSerialVersionUID; if (fw.IsPublic || fw.IsProtected || isSerialVersionUID || includeNonPublicMembers) { object constant = null; if (fw.GetField() != null && fw.GetField().IsLiteral&& (fw.FieldTypeWrapper.IsPrimitive || fw.FieldTypeWrapper == CoreClasses.java.lang.String.Wrapper)) { constant = fw.GetField().GetRawConstantValue(); if (fw.GetField().FieldType.IsEnum) { constant = EnumHelper.GetPrimitiveValue(EnumHelper.GetUnderlyingType(fw.GetField().FieldType), constant); } } IKVM.StubGen.FieldOrMethod f = writer.AddField(fw.Modifiers, fw.Name, fw.Signature.Replace('.', '/'), constant); string sig = tw.GetGenericFieldSignature(fw); if (sig != null) { f.AddAttribute(writer.MakeStringAttribute("Signature", sig)); } if (fw.GetField() != null && fw.GetField().IsDefined(StaticCompiler.Universe.Import(typeof(ObsoleteAttribute)), false)) { f.AddAttribute(new IKVM.StubGen.DeprecatedAttribute(writer)); } } } } if (includeSerialVersionUID && !hasSerialVersionUID && IsSerializable(tw)) { // class is serializable but doesn't have an explicit serialVersionUID, so we add the field to record // the serialVersionUID as we see it (mainly to make the Japi reports more realistic) writer.AddField(Modifiers.Private | Modifiers.Static | Modifiers.Final, "serialVersionUID", "J", IKVM.StubGen.SerialVersionUID.Compute(tw)); } AddMetaAnnotations(writer, tw); zipCount++; MemoryStream mem = new MemoryStream(); writer.Write(mem); ZipEntry entry = new ZipEntry(name + ".class"); entry.Size = mem.Position; zipFile.PutNextEntry(entry); mem.WriteTo(zipFile); }
public ZipEntry(ZipEntry e) { }
public static void ReadDoc() { if (m_DocLoadHelper == null) { throw new System.Exception("m_DocLoadHelper is null"); } byte[] docBytes = m_DocLoadHelper.LoadDoc(filePath); MemoryStream streamm = new MemoryStream(docBytes); byte[] outData = new byte[2048]; //todo 输出操作 string OutPutPath = Path.Combine(Application.dataPath + "/Resources/Test.docx"); ZipOutputStream outputStream = new ZipOutputStream(File.Create(OutPutPath)); outputStream.SetLevel(0); string documentTxt = ""; using (ZipInputStream s = new ZipInputStream(streamm)) { ZipEntry theEntry; while ((theEntry = s.GetNextEntry()) != null) { ZipEntry theEntryOut = new ZipEntry(theEntry.Name); Log.Info(theEntry.Name); outputStream.PutNextEntry(theEntryOut); if (theEntry.Name == "word/media/image2.png") { Texture2D texture2D = Resources.Load <Texture2D>("awen"); byte[] img = texture2D.EncodeToPNG(); outputStream.Write(img, 0, img.Length); } else if (theEntry.Name == "word/media/image3.png") { Texture2D texture2D = Resources.Load <Texture2D>("awen"); byte[] img = texture2D.EncodeToPNG(); outputStream.Write(img, 0, img.Length); } else if (theEntry.Name == "word/media/image11.png") { Texture2D texture2D = Resources.Load <Texture2D>("SignName"); byte[] img = texture2D.EncodeToPNG(); outputStream.Write(img, 0, img.Length); } else { int outSize = s.Read(outData, 0, outData.Length); while (outSize > 0) { if (outSize < outData.Length) { outputStream.Write(outData, 0, outSize); outSize = -1; } else { outputStream.Write(outData, 0, outData.Length); outSize = s.Read(outData, 0, outData.Length); } } } } s.Close(); outputStream.Finish(); outputStream.Close(); } }
/// <summary> /// Adds the <paramref name="zipContentFile"/> as a media object to the <paramref name="album"/>. /// </summary> /// <param name="zipContentFile">A reference to a file in a ZIP archive.</param> /// <param name="album">The album to which the file should be added as a media object.</param> private void AddMediaObjectToGallery(ZipEntry zipContentFile, IAlbum album) { string zipFileName = Path.GetFileName(zipContentFile.Name).Trim(); if (zipFileName.Length == 0) return; string uniqueFilename = HelperFunctions.ValidateFileName(album.FullPhysicalPathOnDisk, zipFileName); string uniqueFilepath = Path.Combine(album.FullPhysicalPathOnDisk, uniqueFilename); // Extract the file from the zip stream and save as the specified filename. ExtractMediaObjectFile(uniqueFilepath); // Get the file we just saved to disk. FileInfo mediaObjectFile = new FileInfo(uniqueFilepath); try { IGalleryObject mediaObject = Factory.CreateMediaObjectInstance(mediaObjectFile, album); HelperFunctions.UpdateAuditFields(mediaObject, this._userName); mediaObject.Save(); if ((_discardOriginalImage) && (mediaObject is Business.Image)) { ((Business.Image)mediaObject).DeleteHiResImage(); mediaObject.Save(); } } catch (ErrorHandler.CustomExceptions.UnsupportedMediaObjectTypeException ex) { this._skippedFiles.Add(new KeyValuePair<string, string>(mediaObjectFile.Name, ex.Message)); File.Delete(mediaObjectFile.FullName); } }
/// <summary> /// 压缩目录到Zip压缩流 /// </summary> /// <param name="outStream">Zip压缩流</param> /// <param name="directoryPath">压缩目录</param> /// <param name="parentPath">相对父级目录</param> private static void ZipDirectoryToZipStream(ZipOutputStream outStream, string directoryPath, string parentPath) { try { if (directoryPath == string.Empty) { return; } if (directoryPath[directoryPath.Length - 1] != '/') { directoryPath += '/'; } if (parentPath[parentPath.Length - 1] != '/') { parentPath += '/'; } ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32(); string[] filePaths = Directory.GetFileSystemEntries(directoryPath); foreach (string path in filePaths) { var filePath = path.Replace('\\', '/'); if (Directory.Exists(filePath)) // 是目录 { string pPath = parentPath + filePath.Substring(filePath.LastIndexOf('/') + 1); pPath += '/'; ZipDirectoryToZipStream(outStream, filePath, pPath); } else { using (FileStream inStream = File.OpenRead(filePath)) { byte[] buffer = new byte[inStream.Length]; inStream.Read(buffer, 0, buffer.Length); inStream.Close(); crc.Reset(); crc.Update(buffer); string entryPath = parentPath + filePath.Substring(filePath.LastIndexOf('/') + 1); ZipEntry zipEntry = new ZipEntry(entryPath); FileInfo fileInfo = new FileInfo(filePath); zipEntry.DateTime = fileInfo.CreationTime > fileInfo.LastWriteTime ? fileInfo.LastWriteTime : fileInfo.CreationTime; zipEntry.Size = fileInfo.Length; zipEntry.Crc = crc.Value; outStream.PutNextEntry(zipEntry); outStream.Write(buffer, 0, buffer.Length); } } } } catch (Exception ex) { throw ex; } }
/// <summary> /// Process a ZIP file that is embedded within the parent ZIP file. Its contents are extracted and turned into /// albums and media objects just like items in the parent ZIP file. /// </summary> /// <param name="zipFile">A reference to a ZIP file contained within the parent ZIP file. Notice that we don't do /// anything with this parameter other than verify that its extension is "ZIP". That's because we actually extract /// the file from the parent ZIP file by calling the ExtractMediaObjectFile method, which extracts the file from /// the class-level member variable _zipStream</param> /// <param name="parentAlbum">The album that should contain the top-level directories and files found in the ZIP /// file.</param> private void ExtractEmbeddedZipFile(ZipEntry zipFile, IAlbum parentAlbum) { #region Validation if (Path.GetExtension(zipFile.Name).ToUpperInvariant() != ".ZIP") { throw new ArgumentException(String.Concat("The zipFile parameter of the method ExtractEmbeddedZipFile in class ZipUtility must be a ZIP file. Instead, it had the file extension ", Path.GetExtension(zipFile.Name), ".")); } if (parentAlbum == null) { throw new ArgumentNullException("parentAlbum"); } #endregion string filepath = Path.Combine(parentAlbum.FullPhysicalPathOnDisk, Guid.NewGuid().ToString("N") + ".config"); try { ExtractMediaObjectFile(filepath); using (ZipUtility zip = new ZipUtility(this._userName, this._roles)) { this._skippedFiles.AddRange(zip.ExtractZipFile(new FileInfo(filepath).OpenRead(), parentAlbum, true)); } } finally { File.Delete(filepath); } }
public void Create_UnicodeEntries() { int i; string origComment = "This is a Unicode comment. " + "Chinese: 弹 出 应 用 程 序 " + "Norwegian/Danish: æøåÆØÅ. " + "Portugese: Configurações."; string[] formats = { "弹出应用程序{0:D3}.bin", "n.æøåÆØÅ{0:D3}.bin", "Configurações-弹出-ÆØÅ-xx{0:D3}.bin", "Symbols®®®-xx{0:D3}.bin" }; for (int k = 0; k < formats.Length; k++) { // create the subdirectory string subdir = Path.Combine(TopLevelDir, "files" + k); Directory.CreateDirectory(subdir); // create a bunch of files int numFilesToCreate = _rnd.Next(18) + 14; string[] filesToZip = new string[numFilesToCreate]; for (i = 0; i < numFilesToCreate; i++) { filesToZip[i] = Path.Combine(subdir, String.Format(formats[k], i)); TestUtilities.CreateAndFillFileBinary(filesToZip[i], _rnd.Next(5000) + 2000); } // create a zipfile twice, once using Unicode, once without for (int j = 0; j < 2; j++) { // select the name of the zip file string zipFileToCreate = Path.Combine(TopLevelDir, String.Format("Create_UnicodeEntries_{0}_{1}.zip", k, j)); Assert.IsFalse(File.Exists(zipFileToCreate), "The zip file '{0}' already exists.", zipFileToCreate); TestContext.WriteLine("\n\nFormat {0}, trial {1}. filename: {2}...", k, j, zipFileToCreate); string dirInArchive = String.Format("{0}-{1}", Path.GetFileName(subdir), j); using (ZipFile zip1 = new ZipFile()) { #pragma warning disable 618 zip1.UseUnicodeAsNecessary = (j == 0); #pragma warning restore 618 for (i = 0; i < filesToZip.Length; i++) { // use the local filename (not fully qualified) ZipEntry e = zip1.AddFile(filesToZip[i], dirInArchive); e.Comment = String.Format("This entry encoded with {0}", (j == 0) ? "unicode" : "the default code page."); } zip1.Comment = origComment; zip1.Save(zipFileToCreate); } // Verify the number of files in the zip Assert.AreEqual <int>(TestUtilities.CountEntries(zipFileToCreate), filesToZip.Length, "Incorrect number of entries in the zip file."); i = 0; // verify the filenames are (or are not) unicode var options = new ReadOptions { Encoding = (j == 0) ? System.Text.Encoding.UTF8 : ZipFile.DefaultEncoding }; using (ZipFile zip2 = FileSystemZip.Read(zipFileToCreate, options)) { foreach (ZipEntry e in zip2) { string fname = String.Format(formats[k], i); if (j == 0) { Assert.AreEqual <String>(fname, Path.GetFileName(e.FileName)); } else { Assert.AreNotEqual <String>(fname, Path.GetFileName(e.FileName)); } i++; } // according to the spec, // unicode is not supported on the zip archive comment! // But this library won't enforce that. // We will leave it up to the application. // Assert.AreNotEqual<String>(origComment, zip2.Comment); } } } }
internal override bool Evaluate(ZipEntry entry) { // swap forward slashes in the entry.FileName for backslashes string transformedFileName = entry.FileName.Replace("/", "\\"); return _Evaluate(transformedFileName); }
private static bool ZipFileDictory(string FolderToZip, ZipOutputStream s, string ParentFolderName, bool separate, string[] files, string[] dirs) { bool res = true; string[] folders, filenames; ZipEntry entry = null; FileStream fs = null; Crc32 crc = new Crc32(); try { //创建当前文件夹 entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/")); //加上 “/” 才会当成是文件夹创建 s.PutNextEntry(entry); s.Flush(); //先压缩文件,再递归压缩文件夹 if (separate) { filenames = files; } else { filenames = Directory.GetFiles(FolderToZip); } foreach (string file in filenames) { //打开压缩文件 fs = File.OpenRead(file); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); string p = Path.GetFileName(FolderToZip); if (p.Length < 1) { p = Path.GetFileName(file); } else { p += "/" + Path.GetFileName(file); } entry = new ZipEntry(Path.Combine(ParentFolderName, p)); entry.DateTime = DateTime.Now; entry.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; s.PutNextEntry(entry); s.Write(buffer, 0, buffer.Length); } } catch { res = false; } finally { if (fs != null) { fs.Close(); fs = null; } if (entry != null) { entry = null; } GC.Collect(); GC.Collect(1); } if (separate) { folders = dirs; } else { folders = Directory.GetDirectories(FolderToZip); } foreach (string folder in folders) { if (folder.Equals(BackUpPath, StringComparison.CurrentCultureIgnoreCase)) { continue; } else if (!ZipFileDictory(folder, s, Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip)), false, null, null)) { return(false); } } return(res); }
internal override bool Evaluate(ZipEntry entry) { return _Evaluate(entry.UncompressedSize); }
public static void UnZip(string FileToUpZip, string ZipedFolder, string Password) { if (!File.Exists(FileToUpZip)) { return; } if (!Directory.Exists(ZipedFolder)) { Directory.CreateDirectory(ZipedFolder); } ZipInputStream s = null; ZipEntry theEntry = null; string fileName; FileStream streamWriter = null; try { s = new ZipInputStream(File.OpenRead(FileToUpZip)); s.Password = Password; while ((theEntry = s.GetNextEntry()) != null) { if (theEntry.Name != String.Empty) { fileName = Path.Combine(ZipedFolder, theEntry.Name); if (fileName.EndsWith("/") || fileName.EndsWith("\\")) { Directory.CreateDirectory(fileName); continue; } streamWriter = File.Create(fileName); int size = 2048; byte[] data = new byte[2048]; while (true) { size = s.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } } } } finally { if (streamWriter != null) { streamWriter.Close(); streamWriter = null; } if (theEntry != null) { theEntry = null; } if (s != null) { s.Close(); s = null; } GC.Collect(); GC.Collect(1); } }
internal override bool Evaluate(ZipEntry entry) { bool result = (ObjectType == 'D') ? entry.IsDirectory : !entry.IsDirectory; if (Operator != ComparisonOperator.EqualTo) result = !result; return result; }
/// <summary> /// Deserializes the portal. /// </summary> /// <param name="file"> /// The file. /// </param> /// <param name="portalName"> /// Name of the portal. /// </param> /// <param name="portalAlias"> /// The portal alias. /// </param> /// <param name="portalPath"> /// The portal path. /// </param> /// <param name="portalId"> /// The portal id. /// </param> /// <returns> /// The deserialize portal. /// </returns> public bool DeserializePortal( string file, string portalName, string portalAlias, string portalPath, string filePath, out int portalId) { var result = true; try { PortalsDTO portal; if (file.EndsWith("AppleSeedTemplates")) { using (var ms = new MemoryStream()) { using (ZipFile zip = ZipFile.Read(GetPhysicalPackageTemplatesPath(filePath) + "\\" + file)) { if (zip.Count == 1) { ms.Position = 0; string name = file.Replace(".AppleSeedTemplates", ".XML"); ZipEntry e = zip[name]; e.Extract(ms); //FileStream s = new FileStream(GetPhysicalPackageTemplatesPath("") + "\\" + name, FileMode.Create); //int pos = int.Parse(ms.Position.ToString()); //s.Write(ms.GetBuffer(), 0, pos); //s.Close(); ms.Position = 0; var xs = new XmlSerializer(typeof(PortalsDTO)); portal = (PortalsDTO)xs.Deserialize(ms); ms.Close(); } else { portal = null; } } // the application can now access the MemoryStream here } } else { var fs = new FileStream(GetPhysicalPackageTemplatesPath(filePath) + "\\" + file, FileMode.Open); var xs = new XmlSerializer(typeof(PortalsDTO)); portal = (PortalsDTO)xs.Deserialize(fs); fs.Close(); } var db = new PortalTemplateDataContext(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString); var desktopSources = this.iptRepository.GetDesktopSources(); var translate = new Translate { DesktopSources = desktopSources, PTDataContext = db }; var _portal = translate.TranslatePortalDTOIntoRb_Portals(portal); this.ModulesNotInserted = translate.ModulesNotInserted; _portal.PortalName = portalName; _portal.PortalPath = portalPath; _portal.PortalAlias = portalAlias; db.rb_Portals.InsertOnSubmit(_portal); db.SubmitChanges(ConflictMode.FailOnFirstConflict); portalId = _portal.PortalID; this.SaveModuleContent(_portal, desktopSources, translate.ContentModules); AlterModuleSettings(_portal, translate.PageList, desktopSources); AlterModuleDefinitions(_portal.PortalID, translate.ModuleDefinitionsDeserialized); } catch (Exception ex) { result = false; portalId = -1; ErrorHandler.Publish(LogLevel.Error, "There was an error on creating the portal", ex); } return(result); }
/// <summary> /// 解压缩单个文件 /// </summary> /// <param name="zipFilePath">压缩文件路径</param> /// <param name="unzipDirectoryPath">解压目录(为空则和压缩文件同级目录)</param> /// <param name="password">解压密码</param> /// <param name="overwrite">是否覆盖已存在文件</param> /// <param name="progressCallback">进度回调</param> public static void UnZipFileEx(string zipFilePath, string unzipDirectoryPath, string password, bool overwrite, Action <string, long, long> progressCallback) { try { if (!File.Exists(zipFilePath)) { throw new Exception("文件" + zipFilePath + "不存在"); } if (unzipDirectoryPath == string.Empty) { unzipDirectoryPath = zipFilePath.Substring(0, zipFilePath.LastIndexOf('/') + 1); if (unzipDirectoryPath == string.Empty) { unzipDirectoryPath = Directory.GetCurrentDirectory(); } } if (!unzipDirectoryPath.EndsWith("/")) { unzipDirectoryPath += "/"; } using (ZipInputStream zipStream = new ZipInputStream(File.OpenRead(zipFilePath))) { zipStream.Password = password; ZipEntry zipEntry = null; while ((zipEntry = zipStream.GetNextEntry()) != null) { if (zipEntry.Name == string.Empty) { continue; } string directoryPath = Path.GetDirectoryName(zipEntry.Name); Directory.CreateDirectory(unzipDirectoryPath + directoryPath); if (!zipEntry.IsDirectory) { if (!File.Exists(unzipDirectoryPath + zipEntry.Name) || overwrite) { using (FileStream outStream = File.Create(unzipDirectoryPath + zipEntry.Name)) { byte[] buffer = new byte[BufferSize]; int size = 0; long maxSize = zipStream.Length; long curSize = size; while (true) { size = zipStream.Read(buffer, 0, BufferSize); if (size <= 0) { break; } outStream.Write(buffer, 0, size); curSize += size; if (progressCallback != null) { progressCallback(zipEntry.Name, curSize, maxSize); } } outStream.Close(); } } } } zipStream.Close(); } } catch (Exception ex) { throw ex; } }
/// <summary> /// 递归压缩文件夹的内部方法 /// </summary> /// <param name="folderToZip">要压缩的文件夹路径</param> /// <param name="zipStream">压缩输出流</param> /// <param name="parentFolderName">此文件夹的上级文件夹</param> /// <returns></returns> private static bool ZipDirectory(string folderToZip, ZipOutputStream zipStream, string parentFolderName) { var result = true; string[] folders, files; ZipEntry ent = null; FileStream fs = null; var crc = new Crc32(); ent = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/")); zipStream.PutNextEntry(ent); zipStream.Flush(); files = Directory.GetFiles(folderToZip); foreach (var file in files) { try { fs = File.OpenRead(file); var buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); ent = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/" + Path.GetFileName(file))); ent.DateTime = DateTime.Now; ent.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); ent.Crc = crc.Value; zipStream.PutNextEntry(ent); zipStream.Write(buffer, 0, buffer.Length); } catch { //result = false; } finally { if (fs != null) { fs.Close(); fs.Dispose(); } if (ent != null) { ent = null; } GC.Collect(); GC.Collect(1); } } folders = Directory.GetDirectories(folderToZip); foreach (var folder in folders) { if (!ZipDirectory(folder, zipStream, folderToZip)) { return(false); } } return(result); }