public static void Main(String[] args) { if (args.Length != 2) Usage(); if (!System.IO.File.Exists(args[0])) { Console.WriteLine("That zip file does not exist!\n"); Usage(); } try { // Specifying Console.Out here causes diagnostic msgs to be sent to the Console // In a WinForms or WPF or Web app, you could specify nothing, or an alternate // TextWriter to capture diagnostic messages. var options = new ReadOptions { StatusMessageWriter = System.Console.Out }; using (ZipFile zip = ZipFile.Read(args[0], options)) { // This call to ExtractAll() assumes: // - none of the entries are password-protected. // - want to extract all entries to current working directory // - none of the files in the zip already exist in the directory; // if they do, the method will throw. zip.ExtractAll(args[1]); } } catch (System.Exception ex1) { System.Console.Error.WriteLine("exception: " + ex1); } }
/// <summary> /// 解压ZIP文件 /// </summary> /// <param name="zipPath">待解压的ZIP文件</param> /// <param name="unZipPath">解压的目录</param> /// <param name="isOverWrite">是否覆盖</param> public static bool Decompress(string zipPath, string unZipPath, bool isOverWrite) { try { ReadOptions options = new ReadOptions(); options.Encoding = Encoding.Default; using (var zip = ZipFile.Read(zipPath, options)) { foreach (ZipEntry entry in zip) { if (string.IsNullOrEmpty(unZipPath)) { unZipPath = zipPath.Split('.').First(); } entry.Extract(unZipPath,isOverWrite ? ExtractExistingFileAction.OverwriteSilently : ExtractExistingFileAction.DoNotOverwrite); } return true; } } catch (Exception) { return false; } }
/// <summary> /// Zipファイルを解凍する。 /// </summary> /// <param name="zipFile">Zipファイルのパス</param> /// <param name="extractDir">解凍先ディレクトリ</param> public static void ZipExtract(string zipFile, string extractDir) { var options = new ReadOptions(); options.Encoding = Encoding.GetEncoding(ShiftJis); using (var zip = ZipFile.Read(zipFile, options)) { zip.ExtractAll(extractDir, ExtractExistingFileAction.Throw); } }
public void Extract(string FilePath, string ExtractPath) { MemoryStream ms = new MemoryStream(); StreamWriter sw = new StreamWriter(ms); ReadOptions options = new ReadOptions(); options.StatusMessageWriter = sw; ZipFile zf = ZipFile.Read(FilePath, options); zf.ExtractAll(ExtractPath); ms.Seek(0, 0); StreamReader sr = new StreamReader(ms); string msg = sr.ReadToEnd(); ConsoleForm._ConsoleFormInstance.richTextBox1AppendText += msg; ConsoleForm._ConsoleFormInstance.richTextBox1AppendText += "Extract Completed"; }
protected override void StartInternal() { try { // Specifying Console.Out here causes diagnostic msgs to be sent to the Console // In a WinForms or WPF or Web app, you could specify nothing, or an alternate // TextWriter to capture diagnostic messages. var options = new ReadOptions { StatusMessageWriter = System.Console.Out }; // TODO change to another writer using (ZipFile zip = ZipFile.Read(zipfile, options)) { //zip.Entries ICollection<ZipEntry> zipFiles = zip.Entries; foreach (ZipEntry ze in zipFiles) { totalSize += ze.UncompressedSize; if (isAborted) throw new Exception("UnzipTask aborted."); } zip.ExtractProgress += new EventHandler<ExtractProgressEventArgs>(EvHandlerExtractProgress); foreach (ZipEntry ze in zipFiles) { ze.Extract(destdir); doneSize += ze.UncompressedSize; if (isAborted) throw new Exception("UnzipTask aborted."); } } status = ITaskStatus.SUCCESS; } catch (ZipException) { status = ITaskStatus.FAIL; statusMsg = "Zip file corrupt or unzip failed. Maybe try again?"; } catch (System.Exception ex1) { status = ITaskStatus.FAIL; statusMsg = ex1.ToString(); } }
/// <summary> /// Unzip files /// </summary> /// <param name="zipFilePath"></param> /// <param name="pathToExtract"></param> public Boolean ExtractZipFile(string zipFilePath, string pathToExtract) { try { var options = new ReadOptions { StatusMessageWriter = System.Console.Out }; using (ZipFile zip = ZipFile.Read(zipFilePath, options)) { // This call to ExtractAll() assumes: // - none of the entries are password-protected. // - want to extract all entries to current working directory // - none of the files in the zip already exist in the directory; // if they do, the method will throw. zip.ExtractAll(pathToExtract); } } catch (Exception) { return false; } return true; }
public Stream GetFileStream(string filepath) { byte[] data; ReadOptions options = new ReadOptions(); using (ZipFile zip = ZipFile.Read(filepath, options)) { if (zip.Entries.Count > 0) { ZipEntry file = zip.Entries.FirstOrDefault(); if (file != null) { data = new byte[file.UncompressedSize]; using (MemoryStream fstream = new MemoryStream(data)) { file.Extract(fstream); } return new MemoryStream(data); } } } return null; }
public static ZipFile Read(Stream zipStream, ZipSegmentedStreamManager segmentsManager, ReadOptions options) { if (segmentsManager == null) { throw new ArgumentNullException("segmentsManager"); } return(Read(zipStream, segmentsManager, options.StatusMessageWriter, options.Encoding, options.ReadProgress, options.FullScan)); }
public void CodePage_UpdateZip_AlternateEncoding_wi10180() { System.Text.Encoding JIS = System.Text.Encoding.GetEncoding("shift_jis"); TestContext.WriteLine("The CP for JIS is: {0}", JIS.CodePage); ReadOptions options = new ReadOptions { Encoding = JIS }; string[] filenames = { "日本語.txt", "日本語テスト.txt" }; // three trials: one for old-style // ProvisionalAlternateEncoding, one for "AsNecessary" // and one for "Always" for (int j=0; j < 3; j++) { string zipFileToCreate = String.Format("wi10180-{0}.zip", j); // pass 1 - create it TestContext.WriteLine("Create zip, cycle {0}...", j); using (var zip = new ZipFile()) { switch (j) { case 0: #pragma warning disable 618 zip.ProvisionalAlternateEncoding = JIS; #pragma warning restore 618 break; case 1: zip.AlternateEncoding = JIS; zip.AlternateEncodingUsage = ZipOption.AsNecessary; break; case 2: zip.AlternateEncoding = JIS; zip.AlternateEncodingUsage = ZipOption.Always; break; } zip.AddEntry(filenames[0], "This is the content for entry (" + filenames[0] + ")"); TestContext.WriteLine("adding file: {0}", filenames[0]); zip.Save(zipFileToCreate); } // pass 2 - read and update it TestContext.WriteLine("Update zip..."); using (var zip0 = ZipFile.Read(zipFileToCreate, options)) { foreach (var e in zip0) { TestContext.WriteLine("existing entry name: {0} encoding: {1}", e.FileName, e.AlternateEncoding.EncodingName ); Assert.AreEqual<System.Text.Encoding> (options.Encoding, e.AlternateEncoding); } zip0.AddEntry(filenames[1], "This is more content..." + System.DateTime.UtcNow.ToString("G")); TestContext.WriteLine("adding file: {0}", filenames[1]); zip0.Save(); } // pass 3 - verify the filenames, again TestContext.WriteLine("Verify zip..."); using (var zip0 = ZipFile.Read(zipFileToCreate, options)) { foreach (string f in filenames) { Assert.AreEqual<string>(f, zip0[f].FileName, "The FileName was not expected, (cycle {0}) ", j); } } } }
public void Extract_ExistingFile() { string zipFileToCreate = Path.Combine(TopLevelDir, "Extract_ExistingFile.zip"); Directory.SetCurrentDirectory(TopLevelDir); string[] filenames = { Path.Combine(SourceDir, "Tools", TestUtilities.GetBinDir("Zipit"), "Zipit.exe"), Path.Combine(SourceDir, TestUtilities.GetBinDir("Zip.Portable"), "Zip.Portable.dll"), Path.Combine(SourceDir, TestUtilities.GetBinDir("Zip.Portable"), "Zip.Portable.pdb"), Path.Combine(SourceDir, TestUtilities.GetBinDir("Zip.Portable"), "Zip.Portable.xml"), //Path.Combine(SourceDir, "AppNote.txt") }; int j = 0; using (ZipFile zip = new ZipFile()) { for (j = 0; j < filenames.Length; j++) zip.AddFile(filenames[j], ""); zip.Comment = "This is a Comment On the Archive"; zip.Save(zipFileToCreate); } BasicVerifyZip(zipFileToCreate); Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), filenames.Length, "The zip file created has the wrong number of entries."); TestContext.WriteLine("- - - - - - - - - - - - - - - - - - - - - - - - - - - -"); TestContext.WriteLine("1. first extract - this should succeed"); var options = new ReadOptions { StatusMessageWriter = new StringWriter() }; using (ZipFile zip = FileSystemZip.Read(zipFileToCreate, options)) { for (j = 0; j < filenames.Length; j++) { var f = Path.GetFileName(filenames[j]); zip[f].Extract("unpack", ExtractExistingFileAction.Throw); } } TestContext.WriteLine(options.StatusMessageWriter.ToString()); TestContext.WriteLine("- - - - - - - - - - - - - - - - - - - - - - - - - - - -"); TestContext.WriteLine("2. extract again - DoNotOverwrite"); options.StatusMessageWriter = new StringWriter(); using (ZipFile zip = FileSystemZip.Read(zipFileToCreate, options)) { for (j = 0; j < filenames.Length; j++) { var f = Path.GetFileName(filenames[j]); zip[f].Extract("unpack", ExtractExistingFileAction.DoNotOverwrite); } } TestContext.WriteLine(options.StatusMessageWriter.ToString()); TestContext.WriteLine("- - - - - - - - - - - - - - - - - - - - - - - - - - - -"); TestContext.WriteLine("3. extract again - OverwriteSilently"); options.StatusMessageWriter = new StringWriter(); using (ZipFile zip = FileSystemZip.Read(zipFileToCreate, options)) { for (j = 0; j < filenames.Length; j++) { var f = Path.GetFileName(filenames[j]); zip[f].Extract("unpack", ExtractExistingFileAction.OverwriteSilently); } } TestContext.WriteLine(options.StatusMessageWriter.ToString()); TestContext.WriteLine("- - - - - - - - - - - - - - - - - - - - - - - - - - - -"); TestContext.WriteLine("4. extract again - InvokeExtractProgressEvent"); options.StatusMessageWriter = new StringWriter(); using (ZipFile zip = FileSystemZip.Read(zipFileToCreate, options)) { zip.ExtractProgress += OverwriteDecider; for (j = 0; j < filenames.Length; j++) { var f = Path.GetFileName(filenames[j]); zip[f].Extract("unpack", ExtractExistingFileAction.InvokeExtractProgressEvent); } } TestContext.WriteLine(options.StatusMessageWriter.ToString()); }
private void UnZipFile(string tempPath, string updatePath) { try { // Specifying Console.Out here causes diagnostic msgs to be sent to the Console // In a WinForms or WPF or Web app, you could specify nothing, or an alternate // TextWriter to capture diagnostic messages. var options = new ReadOptions { StatusMessageWriter = System.Console.Out }; using (ZipFile zip = ZipFile.Read(tempPath, options)) { // This call to ExtractAll() assumes: // - none of the entries are password-protected. // - want to extract all entries to current working directory // - none of the files in the zip already exist in the directory; // if they do, the method will throw. if (Directory.Exists(updatePath)) { DirectoryInfo di = new DirectoryInfo(updatePath); foreach (var file in di.GetFiles()) { file.Delete(); } di.Delete(); } zip.ExtractAll(updatePath); Process.Start(updatePath); } } catch (Exception exp) { Methods.ShowStandardMsgBox(FormMessageType.Error, "خطا","در بازیابی به روز رسانی مشکلی پیش آمد، لطفا مجددا تلاش کنید."); } }
void Unpack() { _Status = "Đang giải nén dữ liệu..."; Application.DoEvents(); tmer.Stop(); try { var options = new ReadOptions { StatusMessageWriter = System.Console.Out }; using (ZipFile zip = ZipFile.Read(PathApp+FilePack, options)) { zip.ExtractAll(PathApp, ExtractExistingFileAction.OverwriteSilently); } // Xóa UpdatePack và cập nhật thông tin version if (File.Exists(PathApp + FilePack)) { File.Delete(PathApp + FilePack); } Xmlconfig xcf = new Xmlconfig("Config.ini", true); xcf.Settings["EmployerInfo/Version"].Value = _Version; xcf.Save("Config.ini"); xcf.Dispose(); RunSoft(); } catch (System.Exception ex) { MessageBox.Show("Quá trình cập nhật gặp lỗi!!!\n\n" + ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Stop); Close(); } }
public static void Main(String[] args) { int startArgs = 0; int i; int codePage = 0; string zipfile = null; string targdir = null; string password = null; List<string> entriesToExtract = new List<String>(); bool extractToConsole = false; ActionDesired action = ActionDesired.Extract; ExtractExistingFileAction behaviorForExistingFile = ExtractExistingFileAction.DoNotOverwrite; bool wantQuiet = false; bool wantFlatten = false; System.IO.Stream bitbucket = System.IO.Stream.Null; System.IO.Stream outstream = null; // because the comments and filenames on zip entries may be UTF-8 //System.Console.OutputEncoding = new System.Text.UTF8Encoding(); if (args.Length == 0) Usage(); if (args[0] == "-") { extractToConsole = true; outstream = Console.OpenStandardOutput(); startArgs = 1; } for (i = startArgs; i < args.Length; i++) { switch (args[i]) { case "-cp": i++; if (args.Length <= i) Usage(); if (codePage != 0) Usage(); System.Int32.TryParse(args[i], out codePage); break; case "-d": i++; if (args.Length <= i) Usage(); if (targdir != null) Usage(); if (extractToConsole) Usage(); if (action != ActionDesired.Extract) Usage(); targdir = args[i]; break; case "-f": wantFlatten = true; if (action != ActionDesired.Extract) Usage(); break; case "-i": if (password != null) Usage(); if (targdir != null) Usage(); if (wantQuiet) Usage(); if (entriesToExtract.Count > 0) Usage(); action = ActionDesired.Info; break; case "-l": if (password != null) Usage(); if (targdir != null) Usage(); if (wantQuiet) Usage(); if (entriesToExtract.Count > 0) Usage(); if (behaviorForExistingFile == ExtractExistingFileAction.OverwriteSilently) Usage(); action = ActionDesired.List; break; case "-o": behaviorForExistingFile = ExtractExistingFileAction.OverwriteSilently; if (action != ActionDesired.Extract) Usage(); break; case "-r": if (wantFlatten == true) Usage(); if (targdir != null) Usage(); if (action == ActionDesired.Test) Usage(); action = ActionDesired.Repair; break; case "-p": i++; if (args.Length <= i) Usage(); if (password != null) Usage(); password = args[i]; break; case "-q": if (action == ActionDesired.List) Usage(); wantQuiet = true; break; case "-t": action = ActionDesired.Test; if (targdir != null) Usage(); //if (wantQuiet) Usage(); if (entriesToExtract.Count > 0) Usage(); break; case "-?": Usage(); break; default: // positional args if (zipfile == null) zipfile = args[i]; else if (action != ActionDesired.Extract) Usage(); else entriesToExtract.Add(args[i]); break; } } if (zipfile == null) { Console.WriteLine("unzip: No zipfile specified.\n"); Usage(); } if (!System.IO.File.Exists(zipfile)) { Console.WriteLine("unzip: That zip file does not exist!\n"); Usage(); } if (targdir == null) targdir = "."; try { if (action == ActionDesired.Repair) { ZipFile.FixZipDirectory(zipfile); } else { var options = new ReadOptions { Encoding = (codePage != 0) ? System.Text.Encoding.GetEncoding(codePage) : null }; using (ZipFile zip = ZipFile.Read(zipfile, options)) { if (entriesToExtract.Count > 0) { // extract specified entries foreach (var entryToExtract in entriesToExtract) { // find the entry ZipEntry e= zip[entryToExtract]; if (e == null) { System.Console.WriteLine(" entry ({0}) does not exist in the zip archive.", entryToExtract); } else { if (wantFlatten) e.FileName = System.IO.Path.GetFileName(e.FileName); if (password == null) { if (e.UsesEncryption) System.Console.WriteLine(" That entry ({0}) requires a password to extract.", entryToExtract); else if (extractToConsole) e.Extract(outstream); else e.Extract(targdir, behaviorForExistingFile); } else { if (extractToConsole) e.ExtractWithPassword(outstream, password); else e.ExtractWithPassword(targdir, behaviorForExistingFile, password); } } } } else if (action == ActionDesired.Info) { System.Console.WriteLine("{0}", zip.Info); } else { // extract all, or list, or test // The logic here does almost the same thing as the ExtractAll() method // on the ZipFile class. But in this case we *could* have control over // it, for example only extract files of a certain type, or whose names // matched a certain pattern, or whose lastmodified times fit a certain // condition, or use a different password for each entry, etc. We can // also display status for each entry, as here. Int64 totalUncompressedSize = 0; bool header = true; foreach (ZipEntry e in zip.EntriesSorted) { if (!wantQuiet) { if (header) { System.Console.WriteLine("Zipfile: {0}", zip.Name); if ((zip.Comment != null) && (zip.Comment != "")) System.Console.WriteLine("Comment: {0}", zip.Comment); System.Console.WriteLine("\n{1,-22} {2,10} {3,5} {4,10} {5,3} {6,8} {0}", "Filename", "Modified", "Size", "Ratio", "Packed", "pw?", "CRC"); System.Console.WriteLine(new System.String('-', 80)); header = false; } totalUncompressedSize += e.UncompressedSize; System.Console.WriteLine("{1,-22} {2,10} {3,5:F0}% {4,10} {5,3} {6:X8} {0}", e.FileName, e.LastModified.ToString("yyyy-MM-dd HH:mm:ss"), e.UncompressedSize, e.CompressionRatio, e.CompressedSize, (e.UsesEncryption) ? "Y" : "N", e.Crc); if ((e.Comment != null) && (e.Comment != "")) System.Console.WriteLine(" Comment: {0}", e.Comment); } if (action == ActionDesired.Extract) { if (e.UsesEncryption) { if (password == null) System.Console.WriteLine("unzip: {0}: Cannot extract this entry without a password.", e.FileName); else { if (wantFlatten) e.FileName = System.IO.Path.GetFileName(e.FileName); if (extractToConsole) e.ExtractWithPassword(outstream, password); else e.ExtractWithPassword(targdir, behaviorForExistingFile, password); } } else { if (wantFlatten) e.FileName = System.IO.Path.GetFileName(e.FileName); if (extractToConsole) e.Extract(outstream); else e.Extract(targdir, behaviorForExistingFile); } } else if (action == ActionDesired.Test) { e.ExtractWithPassword(bitbucket, password); } } // foreach if (!wantQuiet) { System.Console.WriteLine(new System.String('-', 80)); System.Console.WriteLine("{1,-22} {2,10} {3,5} {4,10} {5,3} {6,8} {0}", zip.Entries.Count.ToString() + " files", "", totalUncompressedSize, "", "", "", ""); } } // else (extract all) } // end using(), the underlying file is closed. } } catch (System.Exception ex1) { System.Console.Error.WriteLine("exception: " + ex1); } Console.WriteLine(); }
UnzipOneTextFile ( Byte [] zipFileContents ) { Debug.Assert(zipFileContents != null); Debug.Assert(zipFileContents.Length > 0); using ( MemoryStream oZippedMemoryStream = new MemoryStream(zipFileContents) ) { ReadOptions oReadOptions = new ReadOptions(); oReadOptions.Encoding = Encoding.UTF8; using ( ZipFile oZipFile = ZipFile.Read(oZippedMemoryStream, oReadOptions) ) { ICollection<ZipEntry> oEntries = oZipFile.Entries; if (oEntries.Count != 1) { throw new ApplicationException( "The Zip file does not contain one and only one" + " text file." ); } ZipEntry oTextEntry = oEntries.First(); using ( MemoryStream oUnzippedMemoryStream = new MemoryStream() ) { oTextEntry.Extract(oUnzippedMemoryStream); return ( Encoding.UTF8.GetString( oUnzippedMemoryStream.ToArray() ) ); } } } }
private void downloadFile() { string inputFilePath = txtDir.Text + "\\Temp\\"; string ftpFullPath = host; WebClient request = new WebClient(); request.Credentials = new NetworkCredential(user, pass); byte[] fileData; try { fileData = request.DownloadData(ftpFullPath); } catch(Exception e) { MessageBox.Show(DateTime.Now + " : " + e.Message,"Error connecting to FTP server"); return; } Directory.CreateDirectory(inputFilePath); FileStream file = File.Create(inputFilePath + "GWLXML.zip"); file.Write(fileData, 0, fileData.Length); file.Close(); DirectoryInfo extractDir = new DirectoryInfo(inputFilePath + "extract"); if (extractDir.Exists) { extractDir.Delete(true); } var options = new ReadOptions { StatusMessageWriter = System.Console.Out }; using (ZipFile zip = ZipFile.Read(inputFilePath + "GWLXML.zip", options)) { // This call to ExtractAll() assumes: // - none of the entries are password-protected. // - want to extract all entries to current working directory // - none of the files in the zip already exist in the directory; // if they do, the method will throw. zip.ExtractAll(inputFilePath + "extract"); } DirectoryInfo di = new DirectoryInfo(inputFilePath + "extract"); if (di.Exists) { FileInfo xmlFile = new FileInfo(inputFilePath + "extract\\ENTITY.XML"); if (xmlFile.Exists) { if (xmlFile.LastWriteTime.ToString() != lastTime || lastTime == "") { lastTime = xmlFile.LastWriteTime.Year.ToString() + "_" + xmlFile.LastWriteTime.Month.ToString() + "_" + xmlFile.LastWriteTime.Day.ToString() + "_" + xmlFile.LastWriteTime.Hour.ToString() + "." + xmlFile.LastWriteTime.Minute.ToString(); lblUpdate.Text = xmlFile.LastWriteTime.ToString(); string newDir = txtDir.Text +"\\"+ (lastTime.Replace("/", "").Replace(':', '.')); Directory.CreateDirectory(newDir); File.Copy(inputFilePath + "GWLXML.zip", newDir + "\\GWLXML.zip",true); } } di.Delete(true); } }
internal string BasicVerifyZip(string zipfile, string password, bool emitOutput, EventHandler<ExtractProgressEventArgs> extractProgress) { // basic verification of the zip file - can it be extracted? // The extraction tool will verify checksums and passwords, as appropriate #if NOT if (WinZipIsPresent) { TestContext.WriteLine("Verifying zip file {0} with WinZip", zipfile); string args = (password == null) ? String.Format("-t {0}", zipfile) : String.Format("-s{0} -t {1}", password, zipfile); string wzunzipOut = this.Exec(wzunzip, args, true, emitOutput); } else #endif { TestContext.WriteLine("Verifying zip file {0} with DotNetZip", zipfile); ReadOptions options = new ReadOptions(); if (emitOutput) options.StatusMessageWriter = new StringWriter(); string extractDir = "verify"; int c = 0; while (Directory.Exists(extractDir + c)) c++; extractDir += c; using (ZipFile zip2 = ZipFile.Read(zipfile, options)) { zip2.Password = password; if (extractProgress != null) zip2.ExtractProgress += extractProgress; zip2.ExtractAll(extractDir); } // emit output, as desired if (emitOutput) TestContext.WriteLine("{0}",options.StatusMessageWriter.ToString()); return extractDir; } }
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(zipFileToCreate)) { 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(); } 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 = ZipFile.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."); }
private void Convert() { string TargetName = ZipFileToConvert.Replace(".zip", ".exe"); Console.WriteLine("Converting file {0} to SFX {1}", ZipFileToConvert, TargetName); var options = new ReadOptions { StatusMessageWriter = System.Console.Out }; using (ZipFile zip = ZipFile.Read(ZipFileToConvert, options)) { zip.Comment = ZipComment; SelfExtractorSaveOptions sfxOptions = new SelfExtractorSaveOptions(); sfxOptions.Flavor = flavor; sfxOptions.DefaultExtractDirectory = ExtractDir; sfxOptions.PostExtractCommandLine = ExeOnUnpack; zip.SaveSelfExtractor(TargetName, sfxOptions ); } }
private Boolean Extract(string nhsfile) { // 用输入文件获取要解压缩的文件名 string sfile = file.Replace(".nhs", ".sql"); ReadOptions op = new ReadOptions(); op.Encoding = Encoding.GetEncoding("gb2312"); using (ZipFile zip = ZipFile.Read(nhsfile, op)) { ZipEntry e = zip[sfile]; // comment 的结构 hs_user|06版|1.4.1.4 productid 1, BL4, SP1PACK4 string s = zip.Comment; user = s.Substring(0, s.IndexOf("|")); // 获取脚本用户 // 确定CVSArg s = s.Substring(s.IndexOf("|") + 1); string Product = s.Substring(0, s.IndexOf("|")); s = s.Substring(s.IndexOf("|") + 1); string[] b = s.Split('.'); cv = new CVSArg(Product, int.Parse(b[0]), int.Parse(b[1]), int.Parse(b[2]), int.Parse(b[3])); ms = new MemoryStream(); e.ExtractWithPassword(ms, G_PASS); } return true; }
/// <summary> /// Reads a zip file archive from the given stream using the /// specified options. /// </summary> /// /// <remarks> /// /// <para> /// When reading from a file, it's probably easier to just use /// <see cref="ZipFile.Read(String, /// ReadOptions)">ZipFile.Read(String, ReadOptions)</see>. This /// overload is useful when when the zip archive content is /// available from an already-open stream. The stream must be /// open and readable and seekable when calling this method. The /// stream is left open when the reading is completed. /// </para> /// /// <para> /// Reading of zip content begins at the current position in the /// stream. This means if you have a stream that concatenates /// regular data and zip data, if you position the open, readable /// stream at the start of the zip data, you will be able to read /// the zip archive using this constructor, or any of the ZipFile /// constructors that accept a <see cref="System.IO.Stream" /> as /// input. Some examples of where this might be useful: the zip /// content is concatenated at the end of a regular EXE file, as /// some self-extracting archives do. (Note: SFX files produced /// by DotNetZip do not work this way; they can be read as normal /// ZIP files). Another example might be a stream being read from /// a database, where the zip content is embedded within an /// aggregate stream of data. /// </para> /// </remarks> /// /// <param name="zipStream">the stream containing the zip data.</param> /// /// <param name="options"> /// The set of options to use when reading the zip file. /// </param> /// /// <exception cref="System.Exception"> /// Thrown if the zip archive cannot be read. /// </exception> /// /// <returns>The ZipFile instance read from the stream.</returns> /// /// <seealso cref="ZipFile.Read(String, ReadOptions)"/> /// public static ZipFile Read(Stream zipStream, ReadOptions options) { return Read(zipStream, options.StatusMessageWriter, options.Encoding, options.ReadProgress); }
/// <summary> /// Reads a zip file archive from the named filesystem file using the /// specified options. /// </summary> /// /// <remarks> /// <para> /// This version of the <c>Read()</c> method allows the caller to pass /// in a <c>TextWriter</c> an <c>Encoding</c>, via an instance of the /// <c>ReadOptions</c> class. The <c>ZipFile</c> is read in using the /// specified encoding for entries where UTF-8 encoding is not /// explicitly specified. /// </para> /// </remarks> /// /// <example> /// /// <para> /// This example shows how to read a zip file using the Big-5 Chinese /// code page (950), and extract each entry in the zip file, while /// sending status messages out to the Console. /// </para> /// /// <para> /// For this code to work as intended, the zipfile must have been /// created using the big5 code page (CP950). This is typical, for /// example, when using WinRar on a machine with CP950 set as the /// default code page. In that case, the names of entries within the /// Zip archive will be stored in that code page, and reading the zip /// archive must be done using that code page. If the application did /// not use the correct code page in ZipFile.Read(), then names of /// entries within the zip archive would not be correctly retrieved. /// </para> /// /// <code lang="C#"> /// string zipToExtract = "MyArchive.zip"; /// string extractDirectory = "extract"; /// var options = new ReadOptions /// { /// StatusMessageWriter = System.Console.Out, /// Encoding = System.Text.Encoding.GetEncoding(950) /// }; /// using (ZipFile zip = ZipFile.Read(zipToExtract, options)) /// { /// foreach (ZipEntry e in zip) /// { /// e.Extract(extractDirectory); /// } /// } /// </code> /// /// /// <code lang="VB"> /// Dim zipToExtract as String = "MyArchive.zip" /// Dim extractDirectory as String = "extract" /// Dim options as New ReadOptions /// options.Encoding = System.Text.Encoding.GetEncoding(950) /// options.StatusMessageWriter = System.Console.Out /// Using zip As ZipFile = ZipFile.Read(zipToExtract, options) /// Dim e As ZipEntry /// For Each e In zip /// e.Extract(extractDirectory) /// Next /// End Using /// </code> /// </example> /// /// /// <example> /// /// <para> /// This example shows how to read a zip file using the default /// code page, to remove entries that have a modified date before a given threshold, /// sending status messages out to a <c>StringWriter</c>. /// </para> /// /// <code lang="C#"> /// var options = new ReadOptions /// { /// StatusMessageWriter = new System.IO.StringWriter() /// }; /// using (ZipFile zip = ZipFile.Read("PackedDocuments.zip", options)) /// { /// var Threshold = new DateTime(2007,7,4); /// // We cannot remove the entry from the list, within the context of /// // an enumeration of said list. /// // So we add the doomed entry to a list to be removed later. /// // pass 1: mark the entries for removal /// var MarkedEntries = new System.Collections.Generic.List<ZipEntry>(); /// foreach (ZipEntry e in zip) /// { /// if (e.LastModified < Threshold) /// MarkedEntries.Add(e); /// } /// // pass 2: actually remove the entry. /// foreach (ZipEntry zombie in MarkedEntries) /// zip.RemoveEntry(zombie); /// zip.Comment = "This archive has been updated."; /// zip.Save(); /// } /// // can now use contents of sw, eg store in an audit log /// </code> /// /// <code lang="VB"> /// Dim options as New ReadOptions /// options.StatusMessageWriter = New System.IO.StringWriter /// Using zip As ZipFile = ZipFile.Read("PackedDocuments.zip", options) /// Dim Threshold As New DateTime(2007, 7, 4) /// ' We cannot remove the entry from the list, within the context of /// ' an enumeration of said list. /// ' So we add the doomed entry to a list to be removed later. /// ' pass 1: mark the entries for removal /// Dim MarkedEntries As New System.Collections.Generic.List(Of ZipEntry) /// Dim e As ZipEntry /// For Each e In zip /// If (e.LastModified < Threshold) Then /// MarkedEntries.Add(e) /// End If /// Next /// ' pass 2: actually remove the entry. /// Dim zombie As ZipEntry /// For Each zombie In MarkedEntries /// zip.RemoveEntry(zombie) /// Next /// zip.Comment = "This archive has been updated." /// zip.Save /// End Using /// ' can now use contents of sw, eg store in an audit log /// </code> /// </example> /// /// <exception cref="System.Exception"> /// Thrown if the zipfile cannot be read. The implementation of /// this method relies on <c>System.IO.File.OpenRead</c>, which /// can throw a variety of exceptions, including specific /// exceptions if a file is not found, an unauthorized access /// exception, exceptions for poorly formatted filenames, and so /// on. /// </exception> /// /// <param name="fileName"> /// The name of the zip archive to open. /// This can be a fully-qualified or relative pathname. /// </param> /// /// <param name="options"> /// The set of options to use when reading the zip file. /// </param> /// /// <returns>The ZipFile instance read from the zip archive.</returns> /// /// <seealso cref="ZipFile.Read(Stream, ReadOptions)"/> /// public static ZipFile Read(string fileName, ReadOptions options) { return Read(fileName, options.StatusMessageWriter, options.Encoding, options.ReadProgress); }
/// <summary> /// Reads a zip file archive from the named filesystem file using the /// specified options. /// </summary> /// /// <remarks> /// <para> /// This version of the <c>Read()</c> method allows the caller to pass /// in a <c>TextWriter</c> an <c>Encoding</c>, via an instance of the /// <c>ReadOptions</c> class. The <c>ZipFile</c> is read in using the /// specified encoding for entries where UTF-8 encoding is not /// explicitly specified. /// </para> /// </remarks> /// /// <example> /// /// <para> /// This example shows how to read a zip file using the Big-5 Chinese /// code page (950), and extract each entry in the zip file, while /// sending status messages out to the Console. /// </para> /// /// <para> /// For this code to work as intended, the zipfile must have been /// created using the big5 code page (CP950). This is typical, for /// example, when using WinRar on a machine with CP950 set as the /// default code page. In that case, the names of entries within the /// Zip archive will be stored in that code page, and reading the zip /// archive must be done using that code page. If the application did /// not use the correct code page in ZipFile.Read(), then names of /// entries within the zip archive would not be correctly retrieved. /// </para> /// /// <code lang="C#"> /// string zipToExtract = "MyArchive.zip"; /// string extractDirectory = "extract"; /// var options = new ReadOptions /// { /// StatusMessageWriter = System.Console.Out, /// Encoding = System.Text.Encoding.GetEncoding(950) /// }; /// using (ZipFile zip = ZipFile.Read(zipToExtract, options)) /// { /// foreach (ZipEntry e in zip) /// { /// e.Extract(extractDirectory); /// } /// } /// </code> /// /// /// <code lang="VB"> /// Dim zipToExtract as String = "MyArchive.zip" /// Dim extractDirectory as String = "extract" /// Dim options as New ReadOptions /// options.Encoding = System.Text.Encoding.GetEncoding(950) /// options.StatusMessageWriter = System.Console.Out /// Using zip As ZipFile = ZipFile.Read(zipToExtract, options) /// Dim e As ZipEntry /// For Each e In zip /// e.Extract(extractDirectory) /// Next /// End Using /// </code> /// </example> /// /// /// <example> /// /// <para> /// This example shows how to read a zip file using the default /// code page, to remove entries that have a modified date before a given threshold, /// sending status messages out to a <c>StringWriter</c>. /// </para> /// /// <code lang="C#"> /// var options = new ReadOptions /// { /// StatusMessageWriter = new System.IO.StringWriter() /// }; /// using (ZipFile zip = ZipFile.Read("PackedDocuments.zip", options)) /// { /// var Threshold = new DateTime(2007,7,4); /// // We cannot remove the entry from the list, within the context of /// // an enumeration of said list. /// // So we add the doomed entry to a list to be removed later. /// // pass 1: mark the entries for removal /// var MarkedEntries = new System.Collections.Generic.List<ZipEntry>(); /// foreach (ZipEntry e in zip) /// { /// if (e.LastModified < Threshold) /// MarkedEntries.Add(e); /// } /// // pass 2: actually remove the entry. /// foreach (ZipEntry zombie in MarkedEntries) /// zip.RemoveEntry(zombie); /// zip.Comment = "This archive has been updated."; /// zip.Save(); /// } /// // can now use contents of sw, eg store in an audit log /// </code> /// /// <code lang="VB"> /// Dim options as New ReadOptions /// options.StatusMessageWriter = New System.IO.StringWriter /// Using zip As ZipFile = ZipFile.Read("PackedDocuments.zip", options) /// Dim Threshold As New DateTime(2007, 7, 4) /// ' We cannot remove the entry from the list, within the context of /// ' an enumeration of said list. /// ' So we add the doomed entry to a list to be removed later. /// ' pass 1: mark the entries for removal /// Dim MarkedEntries As New System.Collections.Generic.List(Of ZipEntry) /// Dim e As ZipEntry /// For Each e In zip /// If (e.LastModified < Threshold) Then /// MarkedEntries.Add(e) /// End If /// Next /// ' pass 2: actually remove the entry. /// Dim zombie As ZipEntry /// For Each zombie In MarkedEntries /// zip.RemoveEntry(zombie) /// Next /// zip.Comment = "This archive has been updated." /// zip.Save /// End Using /// ' can now use contents of sw, eg store in an audit log /// </code> /// </example> /// /// <exception cref="System.Exception"> /// Thrown if the zipfile cannot be read. The implementation of /// this method relies on <c>System.IO.File.OpenRead</c>, which /// can throw a variety of exceptions, including specific /// exceptions if a file is not found, an unauthorized access /// exception, exceptions for poorly formatted filenames, and so /// on. /// </exception> /// /// <param name="fileName"> /// The name of the zip archive to open. /// This can be a fully-qualified or relative pathname. /// </param> /// /// <param name="options"> /// The set of options to use when reading the zip file. /// </param> /// /// <returns>The ZipFile instance read from the zip archive.</returns> /// /// <seealso cref="ZipFile.Read(Stream, ReadOptions)"/> /// public static ZipFile Read(string fileName, ReadOptions options) { if (options == null) throw new ArgumentNullException("options"); return Read(fileName, options.StatusMessageWriter, options.Encoding, options.ReadProgress); }
public static ZipFile Read(Stream zipStream, ZipSegmentedStreamManager segmentsManager, ReadOptions options) { if (segmentsManager == null) throw new ArgumentNullException("segmentsManager"); return Read(zipStream, segmentsManager, options.StatusMessageWriter, options.Encoding, options.ReadProgress, options.FullScan); }
private void checkFile() { string zipFilePath = txtDir.Text + "\\Temp\\"; FileInfo theZipFile = new FileInfo(zipFilePath + "GWLXML.zip"); if (!theZipFile.Exists) { downloadFile(); return; } DirectoryInfo extractDir = new DirectoryInfo(zipFilePath + "extract"); if (extractDir.Exists) { extractDir.Delete(true); } var options = new ReadOptions { StatusMessageWriter = System.Console.Out }; using (ZipFile zip = ZipFile.Read(zipFilePath + "GWLXML.zip", options)) { zip.ExtractAll(zipFilePath + "extract"); } DirectoryInfo di = new DirectoryInfo(zipFilePath + "extract"); if (di.Exists) { FileInfo xmlFile = new FileInfo(zipFilePath + "extract\\ENTITY.XML"); if (xmlFile.Exists) { lastTime = xmlFile.LastWriteTime.Year.ToString() + "_" + xmlFile.LastWriteTime.Month.ToString() + "_" + xmlFile.LastWriteTime.Day.ToString() + "_" + xmlFile.LastWriteTime.Hour.ToString() + "." + xmlFile.LastWriteTime.Minute.ToString(); lblUpdate.Text = xmlFile.LastWriteTime.ToString(); } di.Delete(true); } else { downloadFile(); } }
// 上传本地文件,或者删除服务器端文件 // parameters: // strStyle 当包含 delete 的时候,表示要删除 strFilePath 所指的文件 // return: // -2 时间戳不匹配 // -1 一般性错误 // 0 成功 // 其他 成功删除的文件和目录个数 public int WriteFile( string strRootPath, string strFilePath, string strRanges, long lTotalLength, byte[] baSource, string strStyle, byte[] baInputTimestamp, out byte[] baOutputTimestamp, out string strError) { baOutputTimestamp = null; strError = ""; if (String.IsNullOrEmpty(strFilePath) == true) { strError = "strFilePath 参数值不能为空"; return -1; } if (lTotalLength < 0) { strError = "lTotalLength 参数值不能为负数"; return -1; } if (strStyle == null) strStyle = ""; bool bDelete = StringUtil.IsInList("delete", strStyle) == true; if (bDelete == true) { int nDeleteCount = 0; string strDirectory = Path.GetDirectoryName(strFilePath); string strPattern = Path.GetFileName(strFilePath); DirectoryInfo di = new DirectoryInfo(strDirectory); FileSystemInfo[] sis = di.GetFileSystemInfos(strPattern); foreach (FileSystemInfo si in sis) { // 安全性检查:不允许文件和目录越出指定的根目录 if (PathUtil.IsChildOrEqual(si.FullName, strRootPath) == false) continue; if (si is DirectoryInfo) { // 删除一个目录 PathUtil.DeleteDirectory(si.FullName); nDeleteCount++; continue; } if (si is FileInfo) { // 删除一个文件 if (File.Exists(si.FullName) == true) File.Delete(si.FullName); string strNewFilePath1 = GetNewFileName(si.FullName); if (File.Exists(strNewFilePath1) == true) File.Delete(strNewFilePath1); string strRangeFileName = GetRangeFileName(si.FullName); if (File.Exists(strRangeFileName) == true) File.Delete(strRangeFileName); nDeleteCount++; } } return nDeleteCount; } #if NO if (bDelete == true && Directory.Exists(strFilePath) == true) { // 删除一个目录 PathUtil.DeleteDirectory(strFilePath); return 0; } string strNewFilePath = GetNewFileName(strFilePath); if (bDelete == true && File.Exists(strFilePath) == true) { // 删除一个文件 if (File.Exists(strFilePath) == true) File.Delete(strFilePath); if (File.Exists(strNewFilePath) == true) File.Delete(strNewFilePath); string strRangeFileName = GetRangeFileName(strFilePath); if (File.Exists(strRangeFileName) == true) File.Delete(strRangeFileName); return 0; } #endif if (bDelete == false && baSource == null) { strError = "baSource 参数值不能为 null"; return -1; } string strNewFilePath = GetNewFileName(strFilePath); // 确保文件的路径所经过的所有子目录已经创建 PathUtil.CreateDirIfNeed(Path.GetDirectoryName(strFilePath)); //************************************************* // 检查时间戳,当目标文件存在时 if (File.Exists(strFilePath) == true || File.Exists(strNewFilePath) == true) { if (StringUtil.IsInList("ignorechecktimestamp", strStyle) == false) { if (File.Exists(strNewFilePath) == true) baOutputTimestamp = FileUtil.GetFileTimestamp(strNewFilePath); else baOutputTimestamp = FileUtil.GetFileTimestamp(strFilePath); if (ByteArray.Compare(baOutputTimestamp, baInputTimestamp) != 0) { strError = "时间戳不匹配"; return -2; } } } else { if (bDelete == true) { string strRangeFileName = GetRangeFileName(strFilePath); if (File.Exists(strRangeFileName) == true) File.Delete(strRangeFileName); return 0; } // 创建空文件 using (FileStream s = File.Create(strFilePath)) { } baOutputTimestamp = FileUtil.GetFileTimestamp(strFilePath); } #if NO // 删除文件 if (bDelete == true) { if (File.Exists(strFilePath) == true) File.Delete(strFilePath); if (File.Exists(strNewFilePath) == true) File.Delete(strNewFilePath); string strRangeFileName = GetRangeFileName(strFilePath); if (File.Exists(strRangeFileName) == true) File.Delete(strRangeFileName); return 0; } #endif //************************************************** long lCurrentLength = 0; { if (baSource.Length == 0) { if (strRanges != "") { strError = "当 baSource 参数的长度为 0 时,strRanges 的值却为 '" + strRanges + "',不匹配,此时 strRanges 的值应为空字符串"; return -1; } // 把写到 metadata 里的尺寸设好 FileInfo fi = new FileInfo(strFilePath); lCurrentLength = fi.Length; fi = null; } } //****************************************** // 写数据 if (string.IsNullOrEmpty(strRanges) == true) { if (lTotalLength > 0) strRanges = "0-" + Convert.ToString(lTotalLength - 1); else strRanges = ""; } string strRealRanges = strRanges; // 检查本次传来的范围是否是完整的文件。 bool bIsComplete = false; if (lTotalLength == 0) bIsComplete = true; else { // -1 出错 // 0 还有未覆盖的部分 // 1 本次已经完全覆盖 int nState = RangeList.MergeContentRangeString(strRanges, "", lTotalLength, out strRealRanges, out strError); if (nState == -1) { strError = "MergeContentRangeString() error 1 : " + strError + " (strRanges='" + strRanges + "' lTotalLength=" + lTotalLength.ToString() + ")"; return -1; } if (nState == 1) bIsComplete = true; } if (bIsComplete == true) { if (baSource.Length != lTotalLength) { strError = "范围 '" + strRanges + "' 与数据字节数组长度 '" + baSource.Length.ToString() + "' 不符合"; return -1; } } RangeList rangeList = new RangeList(strRealRanges); // 开始写数据 Stream target = null; if (bIsComplete == true) target = File.Create(strFilePath); //一次性发完,直接写到文件 else target = File.Open(strNewFilePath, FileMode.OpenOrCreate); try { int nStartOfBuffer = 0; for (int i = 0; i < rangeList.Count; i++) { RangeItem range = (RangeItem)rangeList[i]; // int nStartOfTarget = (int)range.lStart; int nLength = (int)range.lLength; if (nLength == 0) continue; Debug.Assert(range.lStart >= 0, ""); // 移动目标流的指针到指定位置 target.Seek(range.lStart, SeekOrigin.Begin); target.Write(baSource, nStartOfBuffer, nLength); nStartOfBuffer += nLength; } } finally { target.Close(); } { string strRangeFileName = GetRangeFileName(strFilePath); // 如果一次性写满的情况,需要做下列几件事情: // 1.时间戳以目标文件计算 // 2.写到metadata的长度为目标文件总长度 // 3.如果存在临时辅助文件,则删除这些文件。 // 4. 设置目标文件的 LastWriteTime if (bIsComplete == true) { // baOutputTimestamp = CreateTimestampForCfg(strFilePath); lCurrentLength = lTotalLength; // 删除辅助文件 if (File.Exists(strNewFilePath) == true) File.Delete(strNewFilePath); if (File.Exists(strRangeFileName) == true) File.Delete(strRangeFileName); goto END1; } //**************************************** //处理辅助文件 bool bEndWrite = false; // 是否为最后一次写入操作 string strResultRange = ""; if (strRanges == "" || strRanges == null) { bEndWrite = true; } else { string strOldRanges = ""; if (IsFirstRange(strRanges, lTotalLength, out bEndWrite) == false) { if (File.Exists(strRangeFileName) == true) { string strText = FileUtil.File2StringE(strRangeFileName); string strOldTotalLength = ""; StringUtil.ParseTwoPart(strText, "|", out strOldRanges, out strOldTotalLength); } // return // -1 出错 // 0 还有未覆盖的部分 // 1 本次已经完全覆盖 int nState1 = RangeList.MergeContentRangeString(strRanges, strOldRanges, lTotalLength, out strResultRange, out strError); if (nState1 == -1) { strError = "MergeContentRangeString() error 2 : " + strError + " (strRanges='" + strRanges + "' strOldRanges='" + strOldRanges + "' ) lTotalLength=" + lTotalLength.ToString() + ""; return -1; } if (nState1 == 1) bEndWrite = true; } else { strResultRange = strRanges; } } // 如果文件已满,需要做下列几件事情: // 1.按最大长度截临时文件 // 2.将临时文件拷到目标文件 // 3.删除new,range辅助文件 // 4.时间戳以目标文件计算 // 5.metadata的长度为目标文件的总长度 // 6. 设置目标文件的 LastWriteTime if (bEndWrite == true) { using (Stream s = new FileStream(strNewFilePath, FileMode.OpenOrCreate)) { s.SetLength(lTotalLength); } // TODO: Move 文件较好。改名 File.Delete(strFilePath); File.Move(strNewFilePath, strFilePath); #if NO // 用 .new 临时文件替换直接文件 File.Copy(strNewFilePath, strFilePath, true); File.Delete(strNewFilePath); #endif if (File.Exists(strRangeFileName) == true) File.Delete(strRangeFileName); baOutputTimestamp = FileUtil.GetFileTimestamp(strFilePath); lCurrentLength = lTotalLength; bIsComplete = true; } else { //如果文件未满,需要做下列几件事情: // 1.把目前的range写到range辅助文件 // 2.时间戳以临时文件计算 // 3.metadata的长度为-1,即未知的情况 FileUtil.String2File(strResultRange + "|" + lTotalLength.ToString(), strRangeFileName); lCurrentLength = -1; baOutputTimestamp = FileUtil.GetFileTimestamp(strNewFilePath); } } END1: if (bIsComplete == true) { // 多轮上传的内容完成后,最后需要单独设置文件最后修改时间 string strLastWriteTime = StringUtil.GetStyleParam(strStyle, "last_write_time"); FileUtil.SetFileLastWriteTimeByTimestamp(strFilePath, ByteArray.GetTimeStampByteArray(strLastWriteTime)); baOutputTimestamp = FileUtil.GetFileTimestamp(strFilePath); // 结束时自动展开一个压缩文件 if (StringUtil.IsInList("extractzip", strStyle) == true) { try { ReadOptions option = new ReadOptions(); option.Encoding = Encoding.UTF8; using (ZipFile zip = ZipFile.Read(strFilePath, option)) { foreach (ZipEntry e in zip) { e.Extract(Path.GetDirectoryName(strFilePath), ExtractExistingFileAction.OverwriteSilently); } } File.Delete(strFilePath); } catch (Exception ex) { strError = ex.Message; return -1; } } } #if NO // 写metadata if (strMetadata != "") { string strMetadataFileName = DatabaseUtil.GetMetadataFileName(strFilePath); // 取出旧的数据进行合并 string strOldMetadata = ""; if (File.Exists(strMetadataFileName) == true) strOldMetadata = FileUtil.File2StringE(strMetadataFileName); if (strOldMetadata == "") strOldMetadata = "<file/>"; string strResultMetadata; // return: // -1 出错 // 0 成功 int nRet = DatabaseUtil.MergeMetadata(strOldMetadata, strMetadata, lCurrentLength, out strResultMetadata, out strError); if (nRet == -1) return -1; // 把合并的新数据写到文件里 FileUtil.String2File(strResultMetadata, strMetadataFileName); } #endif return 0; }
/// <summary> /// getReadOptions /// エンコーディングをsift-jisにしないと文字化けするため、オプション指定 /// </summary> /// <returns></returns> private ReadOptions getReadOptions() { ReadOptions ro = new ReadOptions(); ro.Encoding = Encoding.GetEncoding("shift_jis"); return ro; }
/// <summary> /// Reads a zip file archive from the given stream using the /// specified options. /// </summary> /// /// <remarks> /// /// <para> /// When reading from a file, it's probably easier to just use /// <see cref="ZipFile.Read(String, /// ReadOptions)">ZipFile.Read(String, ReadOptions)</see>. This /// overload is useful when when the zip archive content is /// available from an already-open stream. The stream must be /// open and readable and seekable when calling this method. The /// stream is left open when the reading is completed. /// </para> /// /// <para> /// Reading of zip content begins at the current position in the /// stream. This means if you have a stream that concatenates /// regular data and zip data, if you position the open, readable /// stream at the start of the zip data, you will be able to read /// the zip archive using this constructor, or any of the ZipFile /// constructors that accept a <see cref="System.IO.Stream" /> as /// input. Some examples of where this might be useful: the zip /// content is concatenated at the end of a regular EXE file, as /// some self-extracting archives do. (Note: SFX files produced /// by DotNetZip do not work this way; they can be read as normal /// ZIP files). Another example might be a stream being read from /// a database, where the zip content is embedded within an /// aggregate stream of data. /// </para> /// </remarks> /// /// <param name="zipStream">the stream containing the zip data.</param> /// /// <param name="options"> /// The set of options to use when reading the zip file. /// </param> /// /// <exception cref="System.Exception"> /// Thrown if the zip archive cannot be read. /// </exception> /// /// <returns>The ZipFile instance read from the stream.</returns> /// /// <seealso cref="ZipFile.Read(String, ReadOptions)"/> /// internal static ZipFile Read(Stream zipStream, ReadOptions options) { if (options == null) throw new ArgumentNullException("options"); return Read(zipStream, options.StatusMessageWriter, options.Encoding, options.ReadProgress); }
/// <summary> /// Reads a zip file archive from the given stream using the /// specified options. /// </summary> /// /// <remarks> /// /// <para> /// When reading from a file, it's probably easier to just use /// <see cref="ZipFile.Read(String, /// ReadOptions)">ZipFile.Read(String, ReadOptions)</see>. This /// overload is useful when when the zip archive content is /// available from an already-open stream. The stream must be /// open and readable and seekable when calling this method. The /// stream is left open when the reading is completed. /// </para> /// /// <para> /// Reading of zip content begins at the current position in the /// stream. This means if you have a stream that concatenates /// regular data and zip data, if you position the open, readable /// stream at the start of the zip data, you will be able to read /// the zip archive using this constructor, or any of the ZipFile /// constructors that accept a <see cref="System.IO.Stream" /> as /// input. Some examples of where this might be useful: the zip /// content is concatenated at the end of a regular EXE file, as /// some self-extracting archives do. (Note: SFX files produced /// by DotNetZip do not work this way; they can be read as normal /// ZIP files). Another example might be a stream being read from /// a database, where the zip content is embedded within an /// aggregate stream of data. /// </para> /// </remarks> /// /// <param name="zipStream">the stream containing the zip data.</param> /// /// <param name="options"> /// The set of options to use when reading the zip file. /// </param> /// /// <exception cref="System.Exception"> /// Thrown if the zip archive cannot be read. /// </exception> /// /// <returns>The ZipFile instance read from the stream.</returns> /// /// <seealso cref="ZipFile.Read(String, ReadOptions)"/> /// public static ZipFile Read(Stream zipStream, ReadOptions options) { return(ZipFile.Read(zipStream, options)); }
public static ZipFile Read(Stream zipStream, ZipSegmentedStreamManager segmentsManager, ReadOptions options) { return(ZipFile.Read(zipStream, segmentsManager, options)); }
public static bool ExtractZipFile(string zipFilePath, string pathToExtract) { try { var options = new ReadOptions { StatusMessageWriter = System.Console.Out }; using (ZipFile zip = ZipFile.Read(zipFilePath, options)) { zip.ExtractAll(pathToExtract, ExtractExistingFileAction.OverwriteSilently); } } catch (Exception) { return false; } try { File.Delete(zipFilePath); } catch (Exception) { } return true; }
public void Zip64_Over_4gb() { Int64 desiredSize= System.UInt32.MaxValue; desiredSize+= System.Int32.MaxValue/4; desiredSize+= _rnd.Next(0x1000000); _testTitle = "Zip64 Create/Zip/Extract a file > 4.2gb"; _txrx = TestUtilities.StartProgressMonitor("Zip64-Over-4gb", _testTitle, "starting up..."); string zipFileToCreate = Path.Combine(TopLevelDir, "Zip64_Over_4gb.zip"); Directory.SetCurrentDirectory(TopLevelDir); string nameOfFodderFile="VeryVeryLargeFile.txt"; string nameOfExtractedFile = nameOfFodderFile + ".extracted"; // Steps in this test: 4 _txrx.Send("pb 0 max 4"); TestContext.WriteLine(""); TestContext.WriteLine("Creating a large file..." + DateTime.Now.ToString("G")); // create a very large file Action<Int64> progressUpdate = (x) => { _txrx.Send(String.Format("pb 1 value {0}", x)); _txrx.Send(String.Format("status Creating {0}, [{1}/{2}mb] ({3:N0}%)", nameOfFodderFile, x/(1024*1024), desiredSize/(1024*1024), ((double)x)/ (0.01 * desiredSize))); }; // This takes a few minutes... _txrx.Send(String.Format("pb 1 max {0}", desiredSize)); TestUtilities.CreateAndFillFileText(nameOfFodderFile, desiredSize, progressUpdate); // make sure it is larger than 4.2gb FileInfo fi = new FileInfo(nameOfFodderFile); Assert.IsTrue(fi.Length > (long)System.UInt32.MaxValue, "The fodder file ({0}) is not large enough.", nameOfFodderFile); TestContext.WriteLine(""); TestContext.WriteLine("computing checksum..." + DateTime.Now.ToString("G")); _txrx.Send("status computing checksum..."); var chk1 = TestUtilities.ComputeChecksum(nameOfFodderFile); _txrx.Send("pb 0 step"); var sw = new StringWriter(); using (var zip = new ZipFile()) { zip.StatusMessageTextWriter = sw; zip.UseZip64WhenSaving = Zip64Option.Always; zip.BufferSize = 65536*8; // 65536 * 8 = 512k zip.SaveProgress += Zip64SaveProgress; var e = zip.AddFile(nameOfFodderFile, ""); _txrx.Send("status Saving......"); TestContext.WriteLine("zipping one file......" + DateTime.Now.ToString("G")); zip.Save(zipFileToCreate); } EmitStatus(sw.ToString()); File.Delete(nameOfFodderFile); TestContext.WriteLine(""); TestContext.WriteLine("Extracting the zip..." + DateTime.Now.ToString("G")); _txrx.Send("status Extracting the file..."); _txrx.Send("pb 0 step"); var options = new ReadOptions { StatusMessageWriter= new StringWriter() }; verb = "Extracting"; _pb1Set = false; using (var zip = FileSystemZip.Read(zipFileToCreate, options)) { Assert.AreEqual<int>(1, zip.Entries.Count, "Incorrect number of entries in the zip file"); zip.ExtractProgress += Zip64ExtractProgress; _numFilesToExtract = zip.Entries.Count; _numExtracted= 1; ZipEntry e = zip[0]; e.FileName = nameOfExtractedFile; _txrx.Send("status extracting......"); e.Extract(); } EmitStatus(options.StatusMessageWriter.ToString()); _txrx.Send("pb 0 step"); System.Threading.Thread.Sleep(120); TestContext.WriteLine(""); TestContext.WriteLine("computing checksum..." + DateTime.Now.ToString("G")); _txrx.Send("status computing checksum..."); var chk2 = TestUtilities.ComputeChecksum(nameOfExtractedFile); Assert.AreEqual<String>(TestUtilities.CheckSumToString(chk1), TestUtilities.CheckSumToString(chk2), "Checksum mismatch"); _txrx.Send("pb 0 step"); }
public void UnicodeComment_wi10392() { const string zipFileToCreate = "UnicodeComment_wi10392.zip"; const string cyrillicComment = "Hello, Привет"; TestContext.WriteLine("{0}", zipFileToCreate); TestContext.WriteLine("==== creating zip"); using (ZipFile zip1 = new ZipFile(zipFileToCreate, Encoding.UTF8)) { zip1.Comment = cyrillicComment; zip1.AddEntry("entry", "this is the content of the added entry"); zip1.Save(); } string comment2 = null; TestContext.WriteLine("==== checking zip"); var options = new ReadOptions { Encoding = Encoding.UTF8 }; using (ZipFile zip2 = ZipFile.Read(zipFileToCreate, options)) { comment2 = zip2.Comment; } Assert.AreEqual<String>(cyrillicComment, comment2, "The comments are not equal."); }
/// <summary> /// Reads a zip file archive from the named filesystem file using the /// specified options. /// </summary> /// /// <remarks> /// <para> /// This version of the <c>Read()</c> method allows the caller to pass /// in a <c>TextWriter</c> an <c>Encoding</c>, via an instance of the /// <c>ReadOptions</c> class. The <c>ZipFile</c> is read in using the /// specified encoding for entries where UTF-8 encoding is not /// explicitly specified. /// </para> /// </remarks> /// /// <example> /// /// <para> /// This example shows how to read a zip file using the Big-5 Chinese /// code page (950), and extract each entry in the zip file, while /// sending status messages out to the Console. /// </para> /// /// <para> /// For this code to work as intended, the zipfile must have been /// created using the big5 code page (CP950). This is typical, for /// example, when using WinRar on a machine with CP950 set as the /// default code page. In that case, the names of entries within the /// Zip archive will be stored in that code page, and reading the zip /// archive must be done using that code page. If the application did /// not use the correct code page in ZipFile.Read(), then names of /// entries within the zip archive would not be correctly retrieved. /// </para> /// /// <code lang="C#"> /// string zipToExtract = "MyArchive.zip"; /// string extractDirectory = "extract"; /// var options = new ReadOptions /// { /// StatusMessageWriter = System.Console.Out, /// Encoding = System.Text.Encoding.GetEncoding(950) /// }; /// using (ZipFile zip = ZipFile.Read(zipToExtract, options)) /// { /// foreach (ZipEntry e in zip) /// { /// e.Extract(extractDirectory); /// } /// } /// </code> /// /// /// <code lang="VB"> /// Dim zipToExtract as String = "MyArchive.zip" /// Dim extractDirectory as String = "extract" /// Dim options as New ReadOptions /// options.Encoding = System.Text.Encoding.GetEncoding(950) /// options.StatusMessageWriter = System.Console.Out /// Using zip As ZipFile = ZipFile.Read(zipToExtract, options) /// Dim e As ZipEntry /// For Each e In zip /// e.Extract(extractDirectory) /// Next /// End Using /// </code> /// </example> /// /// /// <example> /// /// <para> /// This example shows how to read a zip file using the default /// code page, to remove entries that have a modified date before a given threshold, /// sending status messages out to a <c>StringWriter</c>. /// </para> /// /// <code lang="C#"> /// var options = new ReadOptions /// { /// StatusMessageWriter = new System.IO.StringWriter() /// }; /// using (ZipFile zip = ZipFile.Read("PackedDocuments.zip", options)) /// { /// var Threshold = new DateTime(2007,7,4); /// // We cannot remove the entry from the list, within the context of /// // an enumeration of said list. /// // So we add the doomed entry to a list to be removed later. /// // pass 1: mark the entries for removal /// var MarkedEntries = new System.Collections.Generic.List<ZipEntry>(); /// foreach (ZipEntry e in zip) /// { /// if (e.LastModified < Threshold) /// MarkedEntries.Add(e); /// } /// // pass 2: actually remove the entry. /// foreach (ZipEntry zombie in MarkedEntries) /// zip.RemoveEntry(zombie); /// zip.Comment = "This archive has been updated."; /// zip.Save(); /// } /// // can now use contents of sw, eg store in an audit log /// </code> /// /// <code lang="VB"> /// Dim options as New ReadOptions /// options.StatusMessageWriter = New System.IO.StringWriter /// Using zip As ZipFile = ZipFile.Read("PackedDocuments.zip", options) /// Dim Threshold As New DateTime(2007, 7, 4) /// ' We cannot remove the entry from the list, within the context of /// ' an enumeration of said list. /// ' So we add the doomed entry to a list to be removed later. /// ' pass 1: mark the entries for removal /// Dim MarkedEntries As New System.Collections.Generic.List(Of ZipEntry) /// Dim e As ZipEntry /// For Each e In zip /// If (e.LastModified < Threshold) Then /// MarkedEntries.Add(e) /// End If /// Next /// ' pass 2: actually remove the entry. /// Dim zombie As ZipEntry /// For Each zombie In MarkedEntries /// zip.RemoveEntry(zombie) /// Next /// zip.Comment = "This archive has been updated." /// zip.Save /// End Using /// ' can now use contents of sw, eg store in an audit log /// </code> /// </example> /// /// <exception cref="System.Exception"> /// Thrown if the zipfile cannot be read. The implementation of /// this method relies on <c>System.IO.File.OpenRead</c>, which /// can throw a variety of exceptions, including specific /// exceptions if a file is not found, an unauthorized access /// exception, exceptions for poorly formatted filenames, and so /// on. /// </exception> /// /// <param name="zipFileName"> /// The name of the zip archive to open. /// This can be a fully-qualified or relative pathname. /// </param> /// /// <param name="options"> /// The set of options to use when reading the zip file. /// </param> /// /// <returns>The ZipFile instance read from the zip archive.</returns> /// /// <seealso cref="ZipFile.Read(Stream, ReadOptions)"/> /// public static ZipFile Read(string zipFileName, ReadOptions options) { return(ZipFileExtensions.Read(zipFileName, options)); }
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" }; 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 = ZipFile.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); } } } }