本文整理汇总了C#中Ionic.Zip.ZipFile.SaveSelfExtractor方法的典型用法代码示例。如果您正苦于以下问题:C# ZipFile.SaveSelfExtractor方法的具体用法?C# ZipFile.SaveSelfExtractor怎么用?C# ZipFile.SaveSelfExtractor使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Ionic.Zip.ZipFile
的用法示例。
在下文中一共展示了ZipFile.SaveSelfExtractor方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateSelfExtractingZip
/// <summary>
/// Create a self-extracting ZIP using the DoNetZip library
/// </summary>
public static void CreateSelfExtractingZip(string outputFile, string tempFilePath, string productVersion, string productDescription, string installPath, string postExtractCommand)
{
if (!String.IsNullOrEmpty(outputFile))
{
using (var zip = new ZipFile())
{
zip.AddDirectory(tempFilePath);
var options = new SelfExtractorSaveOptions
{
ProductName = productDescription,
ProductVersion = productVersion,
FileVersion = new System.Version(productVersion),
Description = productDescription,
Copyright = "Copyright © Influence Health 2015",
DefaultExtractDirectory = installPath,
Flavor = SelfExtractorFlavor.WinFormsApplication,
Quiet = false,
RemoveUnpackedFilesAfterExecute = false,
IconFile = Environment.CurrentDirectory + @"\Installer.ico",
ExtractExistingFile = ExtractExistingFileAction.OverwriteSilently,
PostExtractCommandLine = postExtractCommand
};
zip.SaveSelfExtractor(outputFile, options);
}
}
}
示例2: button1_Click
private void button1_Click(object sender, EventArgs e)
{
if (!created)
{
string DirectoryPath = @"C:\SOURCE\DSPControlCenter\Setup\Setup\Express\SingleImage\DiskImages\DISK1";
using (ZipFile zip = new ZipFile())
{
zip.AddDirectory(DirectoryPath, System.IO.Path.GetFileName(DirectoryPath));
zip.Comment = "This will be embedded into a self-extracting console-based exe";
SelfExtractorSaveOptions options = new SelfExtractorSaveOptions();
options.Flavor = SelfExtractorFlavor.ConsoleApplication;
options.Quiet = true;
options.DefaultExtractDirectory = "%TEMP%\\DSPCC";
options.PostExtractCommandLine = "%TEMP%\\DSPCC\\DISK1\\setup.exe";
options.RemoveUnpackedFilesAfterExecute = true;
options.FileVersion = new Version(2, 1, 0);
options.Description = "DSP Control Center Installer Package";
options.Copyright = "© 2013 Stewart Audio, Inc.";
options.IconFile = @"C:\SOURCE\DSPControlCenter\DSP Control Center v4.ico";
options.ProductName = "DSP Control Center";
options.ProductVersion = "2.1.0";
options.ExtractExistingFile = ExtractExistingFileAction.OverwriteSilently;
zip.SaveSelfExtractor(txtFilename.Text + " v" + txtVersion.Text + ".exe", options);
button1.Text = "Open Folder";
created = true;
}
} else
{
string myPath = @"C:\SOURCE\DSPControlCenter\Setup\SetupLauncher\SetupLauncher\bin\Debug";
System.Diagnostics.Process prc = new System.Diagnostics.Process();
prc.StartInfo.FileName = myPath;
prc.Start();
}
}
示例3: ShellApplication_Unzip_SFX
public void ShellApplication_Unzip_SFX()
{
// get a set of files to zip up
string subdir = Path.Combine(TopLevelDir, "files");
string[] filesToZip;
Dictionary<string, byte[]> checksums;
CreateFilesAndChecksums(subdir, out filesToZip, out checksums);
var script = GetScript("VbsUnzip-ShellApp.vbs");
int i=0;
foreach (var compLevel in compLevels)
{
// create and fill the directories
string zipFileToCreate = Path.Combine(TopLevelDir, String.Format("ShellApp_Unzip_SFX.{0}.exe", i));
string extractDir = Path.Combine(TopLevelDir, String.Format("extract.{0}",i));
// Create the zip archive
using (ZipFile zip1 = new ZipFile())
{
zip1.CompressionLevel = (Ionic.Zlib.CompressionLevel) compLevel;
//zip.StatusMessageTextWriter = System.Console.Out;
for (int j = 0; j < filesToZip.Length; j++)
zip1.AddItem(filesToZip[j], "files");
zip1.SaveSelfExtractor(zipFileToCreate, SelfExtractorFlavor.ConsoleApplication);
}
// Verify the number of files in the zip
Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate), filesToZip.Length,
"Incorrect number of entries in the zip file.");
// run the unzip script
this.Exec(cscriptExe,
String.Format("\"{0}\" {1} {2}", script, zipFileToCreate, extractDir));
// check the files in the extract dir
VerifyChecksums(Path.Combine(extractDir, "files"), filesToZip, checksums);
// verify the file times
VerifyTimesDos(Path.Combine(extractDir, "files"), filesToZip);
i++;
}
}
示例4: Winzip_Unzip_SFX
public void Winzip_Unzip_SFX()
{
if (!WinZipIsPresent)
throw new Exception("[Winzip_Unzip_SFX] : winzip is not present");
string zipFileToCreate = "Winzip_Unzip_SFX.exe";
// create and fill the directories
string extractDir = Path.Combine(TopLevelDir, "extract");
string subdir = Path.Combine(TopLevelDir, "files");
Dictionary<string, byte[]> checksums = new Dictionary<string, byte[]>();
var filesToZip = GetSelectionOfTempFiles(_rnd.Next(13) + 8, checksums);
// Create the zip archive
using (ZipFile zip1 = new ZipFile())
{
zip1.AddFiles(filesToZip, "files");
zip1.SaveSelfExtractor(zipFileToCreate,
SelfExtractorFlavor.ConsoleApplication);
}
// Verify the number of files in the zip
Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate),
filesToZip.Count,
"Incorrect number of entries in the zip file.");
// now, extract the zip
// eg, wzunzip.exe -d test.zip [<extractdir>]
Directory.CreateDirectory(extractDir);
Directory.SetCurrentDirectory(extractDir);
// -d = restore folder structure
// -yx = restore extended timestamps to extracted files
this.Exec(wzunzip, "-d -yx " + Path.Combine("..", zipFileToCreate));
// check the files in the extract dir
VerifyChecksums(Path.Combine(extractDir, "files"), filesToZip, checksums);
// verify the file times
VerifyTimesDos(Path.Combine(extractDir, "files"), filesToZip);
}
示例5: SevenZip_Unzip_SFX
public void SevenZip_Unzip_SFX()
{
if (!SevenZipIsPresent)
throw new Exception("[7z_Unzip_SFX] : SevenZip is not present");
string zipFileToCreate = Path.Combine(TopLevelDir, "7z_Unzip_SFX.exe");
// create and fill the directories
string subdir = Path.Combine(TopLevelDir, "files");
string[] filesToZip;
Dictionary<string, byte[]> checksums;
CreateFilesAndChecksums(subdir, out filesToZip, out checksums);
// Create the zip archive with DotNetZip
//Directory.SetCurrentDirectory(TopLevelDir);
using (ZipFile zip1 = new ZipFile())
{
for (int i = 0; i < filesToZip.Length; i++)
zip1.AddItem(filesToZip[i], "files");
zip1.SaveSelfExtractor(zipFileToCreate,
SelfExtractorFlavor.ConsoleApplication);
}
// Verify the number of files in the zip
Assert.AreEqual<int>(TestUtilities.CountEntries(zipFileToCreate),
filesToZip.Length,
"Incorrect number of entries in the zip file.");
// unpack the zip archive via 7z.exe
Directory.CreateDirectory("extract");
Directory.SetCurrentDirectory("extract");
this.Exec(sevenZip, String.Format("x {0}", zipFileToCreate));
// check the files in the extract dir
Directory.SetCurrentDirectory(TopLevelDir);
VerifyChecksums(Path.Combine("extract", "files"), filesToZip, checksums);
}
示例6: Main
//.........这里部分代码省略.........
case "-UTnewest":
_UseUniformTimestamp = 2;
break;
case "-UToldest":
_UseUniformTimestamp = 3;
break;
case "-UT":
i++;
if (args.Length <= i) Usage();
_UseUniformTimestamp = 4;
try
{
_fixedTimestamp= System.DateTime.Parse(args[i]);
}
catch
{
throw new ArgumentException("-UT");
}
break;
case "-utf8":
zip.AlternateEncoding = System.Text.Encoding.UTF8;
zip.AlternateEncodingUsage = ZipOption.Always;
break;
#if NOT
case "-c":
i++;
if (args.Length <= i) Usage();
entryComment = args[i]; // for the next entry
break;
#endif
case "-zc":
i++;
if (args.Length <= i) Usage();
zip.Comment = args[i];
break;
default:
// UpdateItem will add Files or Dirs,
// recurses subdirectories
actualItem = Path.Combine(directoryOnDisk ?? ".", args[i]);
zip.UpdateItem(actualItem, entryDirectoryPathInArchive);
break;
}
}
if (_UseUniformTimestamp > 0)
{
if (_UseUniformTimestamp==2)
{
// newest
_fixedTimestamp = new System.DateTime(1601,1,1,0,0,0);
foreach(var entry in zip)
{
if (entry.LastModified > _fixedTimestamp)
_fixedTimestamp = entry.LastModified;
}
}
else if (_UseUniformTimestamp==3)
{
// oldest
foreach(var entry in zip)
{
if (entry.LastModified < _fixedTimestamp)
_fixedTimestamp = entry.LastModified;
}
}
foreach(var entry in zip)
{
entry.LastModified = _fixedTimestamp;
}
}
if (!flavor.HasValue)
{
if (saveToStdout)
zip.Save(Console.OpenStandardOutput());
else
zip.Save();
}
else
{
if (saveToStdout)
throw new Exception("Cannot save SFX to stdout, sorry! See http://dotnetzip.codeplex.com/WorkItem/View.aspx?WorkItemId=7246");
zip.SaveSelfExtractor(args[0], flavor.Value);
}
}
}
catch (System.Exception ex1)
{
System.Console.WriteLine("Exception: " + ex1);
}
}
示例7: run
public void run()
{
logger.Info("Making archive [what's it called?]");
using (ZipFile zip = new ZipFile())
{
if (Directory.Exists(SourceDir))
{
zip.AddDirectory(SourceDir, Path.GetFileName(SourceDir));
}
else
{
// logger?
Console.WriteLine("{0} is not a valid directory", SourceDir);
Environment.Exit(1);
}
// these files install and log the patch
zip.AddFile("Clyde.exe");
zip.AddFile("PatchLib.dll");
zip.AddFile("Nini.dll");
zip.AddFile("NLog.dll");
zip.AddFile("NLog.config");
SelfExtractorSaveOptions options = new SelfExtractorSaveOptions();
options.Flavor = SelfExtractorFlavor.ConsoleApplication;
options.ProductVersion = VersionInfo.PRODUCT_VERSION;
options.DefaultExtractDirectory = ExtractDir;
options.Copyright = VersionInfo.COPYRIGHT;
options.PostExtractCommandLine = "Clyde.exe";
// false for dev, (maybe) true for production
options.RemoveUnpackedFilesAfterExecute = false;
string patchName = @"envision-installer-" + PatchVersion + @".exe";
zip.SaveSelfExtractor(patchName, options);
}
}
示例8: SFX_RemoveFilesAfterUnpack_wi10682
public void SFX_RemoveFilesAfterUnpack_wi10682()
{
string subdir = "files";
string[] filesToZip;
Dictionary<string, byte[]> checksums;
CreateFilesAndChecksums(subdir, out filesToZip, out checksums);
string password = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
string postExeFormat = "post-extract-{0:D4}.exe";
string postExtractExe = String.Format(postExeFormat, _rnd.Next(10000));
CompileApp(0, postExtractExe);
// pass 1 to run SFX and verify files are present;
// pass 2 to run SFX and verify that it deletes files after extracting.
// 2 passes: one for no cmd line overload, one with overload of -r+/-r-
for (int j=0; j < 2; j++)
{
// 2 passes: with RemoveUnpackedFiles set or unset
for (int k=0; k < 2; k++)
{
string sfxFileToCreate =
String.Format("SFX_RemoveFilesAfterUnpack.{0}.{1}.exe",j,k);
using (ZipFile zip = new ZipFile())
{
zip.Password = password;
zip.Encryption = Ionic.Zip.EncryptionAlgorithm.WinZipAes256;
Array.ForEach(filesToZip, x => { zip.AddFile(x, "files");});
zip.AddFile(postExtractExe, "files");
var sfxOptions = new SelfExtractorSaveOptions
{
Flavor = SelfExtractorFlavor.ConsoleApplication,
Quiet = true,
PostExtractCommandLine = Path.Combine("files",postExtractExe)
};
if (k==1)
sfxOptions.RemoveUnpackedFilesAfterExecute = true;
zip.SaveSelfExtractor(sfxFileToCreate, sfxOptions);
}
string extractDir = String.Format("extract.{0}.{1}",j,k);
string sfxCmdLineArgs =
String.Format("-p {0} -d {1}", password, extractDir);
if (j==1)
{
// override the option set at time of zip.SaveSfx()
sfxCmdLineArgs += (k==0) ? " -r+" : " -r-";
}
// invoke the SFX
this.Exec(sfxFileToCreate, sfxCmdLineArgs, true, true);
if (k==j)
{
// verify that the files are extracted, and match
VerifyChecksums(Path.Combine(extractDir, "files"),
filesToZip, checksums);
}
else
{
// verify that no files exist in the extract directory
var remainingFiles = Directory.GetFiles(extractDir);
Assert.IsTrue(remainingFiles.Length == 0);
}
}
}
}
示例9: SFX_Save_Zip_As_EXE
public void SFX_Save_Zip_As_EXE()
{
string sfxFileToCreate = "SFX_Save_Zip_As_EXE.exe";
// create a file to zip
string subdir = "files";
Directory.CreateDirectory(subdir);
string filename = Path.Combine(subdir, "file1.txt");
TestUtilities.CreateAndFillFileText(filename, _rnd.Next(34000) + 5000);
// add an entry to the zipfile, then try saving to a directory. this should fail
using (ZipFile zip = new ZipFile())
{
zip.AddFile(filename, "");
zip.SaveSelfExtractor(sfxFileToCreate,
SelfExtractorFlavor.ConsoleApplication);
}
// create another file
filename = Path.Combine(subdir, "file2.txt");
TestUtilities.CreateAndFillFileText(filename, _rnd.Next(34000) + 5000);
// update the SFX, save to a zip format
using (ZipFile zip = ZipFile.Read(sfxFileToCreate))
{
zip.AddFile(filename, "");
zip.Save(); // FAIL
}
}
示例10: _Internal_SelfExtractor_Command
public void _Internal_SelfExtractor_Command(string cmdFormat,
SelfExtractorFlavor flavor,
bool runSfx,
bool quiet,
bool forceNoninteractive,
bool wantArgs)
{
TestContext.WriteLine("==============================");
TestContext.WriteLine("SFX_RunOnExit({0})", flavor.ToString());
//int entriesAdded = 0;
//String filename = null;
string postExtractExe = String.Format(cmdFormat, _rnd.Next(3000));
// If WinForms and want forceNoninteractive, have the post-extract-exe return 0,
// else, select a random number.
int expectedReturnCode = (forceNoninteractive &&
flavor == SelfExtractorFlavor.WinFormsApplication)
? 0
: _rnd.Next(1024) + 20;
TestContext.WriteLine("The post-extract command ({0}) will return {1}",
postExtractExe, expectedReturnCode);
string subdir = "A";
string[] filesToZip;
Dictionary<string, byte[]> checksums;
CreateFilesAndChecksums(subdir, out filesToZip, out checksums);
for (int k = 0; k < 2; k++)
{
string readmeString =
String.Format("Hey! This zipfile entry was created directly from " +
"a string in application code. Flavor ({0}) Trial({1})",
flavor.ToString(), k);
string exeFileToCreate = String.Format("SFX_Command.{0}.{1}.exe",
flavor.ToString(), k);
TestContext.WriteLine("----------------------");
TestContext.WriteLine("Trial {0}", k);
string unpackDir = String.Format("unpack.{0}", k);
var sw = new System.IO.StringWriter();
using (ZipFile zip = new ZipFile())
{
zip.StatusMessageTextWriter = sw;
zip.AddDirectory(subdir, subdir); // Path.GetFileName(subdir));
zip.Comment = String.Format("Trial options: fl({0}) cmd ({3})\r\n"+
"actuallyRun({1})\r\nquiet({2})\r\n"+
"exists? {4}\r\nexpected rc={5}",
flavor,
runSfx,
quiet,
postExtractExe,
k!=0,
expectedReturnCode
);
var ms1 = new MemoryStream(Encoding.UTF8.GetBytes(readmeString));
zip.AddEntry("Readme.txt", ms1);
if (k != 0)
{
CompileApp(expectedReturnCode, postExtractExe);
zip.AddFile(postExtractExe);
}
var sfxOptions = new SelfExtractorSaveOptions
{
Flavor = flavor,
DefaultExtractDirectory = unpackDir,
SfxExeWindowTitle = "Custom SFX Title " + DateTime.Now.ToString("G"),
Quiet = quiet
};
// In the case of k==0, this exe does not exist. It will result in
// a return code of 5. In k == 1, the exe exists and will succeed.
if (postExtractExe.Contains(' '))
sfxOptions.PostExtractCommandLine= "\"" + postExtractExe + "\"";
else
sfxOptions.PostExtractCommandLine= postExtractExe;
if (wantArgs)
sfxOptions.PostExtractCommandLine += " arg1 arg2";
zip.SaveSelfExtractor(exeFileToCreate, sfxOptions);
}
TestContext.WriteLine("status output: " + sw.ToString());
if (k != 0) File.Delete(postExtractExe);
// Run the generated Self-extractor, conditionally.
//
// We always run, unless specifically asked not to, OR if it's a
// winforms app and we want it to be noninteractive and there's no
// EXE to run. If we try running a non-existent app, it will pop an
// error message, hence user interaction, which we need to avoid for
// the automated test.
if (runSfx &&
(k != 0 || !forceNoninteractive ||
flavor != SelfExtractorFlavor.WinFormsApplication))
{
//.........这里部分代码省略.........
示例11: SFX_CanRead
public void SFX_CanRead()
{
SelfExtractorFlavor[] flavors =
{
SelfExtractorFlavor.ConsoleApplication,
SelfExtractorFlavor.WinFormsApplication
};
for (int k = 0; k < flavors.Length; k++)
{
string sfxFileToCreate = Path.Combine(TopLevelDir, String.Format("SFX_{0}.exe", flavors[k].ToString()));
string unpackDir = Path.Combine(TopLevelDir, "unpack");
if (Directory.Exists(unpackDir))
Directory.Delete(unpackDir, true);
string readmeString = "Hey there! This zipfile entry was created directly from a string in application code.";
int entriesAdded = 0;
String filename = null;
string Subdir = Path.Combine(TopLevelDir, String.Format("A{0}", k));
Directory.CreateDirectory(Subdir);
var checksums = new Dictionary<string, string>();
int fileCount = _rnd.Next(50) + 30;
for (int j = 0; j < fileCount; j++)
{
filename = Path.Combine(Subdir, String.Format("file{0:D3}.txt", j));
TestUtilities.CreateAndFillFileText(filename, _rnd.Next(34000) + 5000);
entriesAdded++;
var chk = TestUtilities.ComputeChecksum(filename);
checksums.Add(filename.Replace(TopLevelDir + "\\", "").Replace('\\', '/'), TestUtilities.CheckSumToString(chk));
}
using (ZipFile zip1 = new ZipFile())
{
zip1.AddDirectory(Subdir, Path.GetFileName(Subdir));
zip1.Comment = "This will be embedded into a self-extracting exe";
MemoryStream ms1 = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(readmeString));
zip1.AddEntry("Readme.txt", ms1);
zip1.SaveSelfExtractor(sfxFileToCreate, flavors[k]);
}
TestContext.WriteLine("---------------Reading {0}...", sfxFileToCreate);
using (ZipFile zip2 = ZipFile.Read(sfxFileToCreate))
{
//string extractDir = String.Format("extract{0}", j);
foreach (var e in zip2)
{
TestContext.WriteLine(" Entry: {0} c({1}) u({2})", e.FileName, e.CompressedSize, e.UncompressedSize);
e.Extract(unpackDir);
if (!e.IsDirectory)
{
if (checksums.ContainsKey(e.FileName))
{
filename = Path.Combine(unpackDir, e.FileName);
string actualCheckString = TestUtilities.CheckSumToString(TestUtilities.ComputeChecksum(filename));
Assert.AreEqual<string>(checksums[e.FileName], actualCheckString, "In trial {0}, Checksums for ({1}) do not match.", k, e.FileName);
}
else
{
Assert.AreEqual<string>("Readme.txt", e.FileName, String.Format("trial {0}", k));
}
}
}
}
}
}
示例12: SFX_WinForms
public void SFX_WinForms()
{
string[] Passwords = { null, "12345" };
for (int k = 0; k < Passwords.Length; k++)
{
string exeFileToCreate = Path.Combine(TopLevelDir, String.Format("SFX_WinForms-{0}.exe", k));
string DesiredunpackDir = Path.Combine(TopLevelDir, String.Format("unpack{0}", k));
String filename = null;
string Subdir = Path.Combine(TopLevelDir, String.Format("A{0}", k));
Directory.CreateDirectory(Subdir);
var checksums = new Dictionary<string, string>();
int fileCount = _rnd.Next(10) + 10;
for (int j = 0; j < fileCount; j++)
{
filename = Path.Combine(Subdir, String.Format("file{0:D3}.txt", j));
TestUtilities.CreateAndFillFileText(filename, _rnd.Next(34000) + 5000);
var chk = TestUtilities.ComputeChecksum(filename);
checksums.Add(filename, TestUtilities.CheckSumToString(chk));
}
using (ZipFile zip = new ZipFile())
{
zip.Password = Passwords[k];
zip.AddDirectory(Subdir, Path.GetFileName(Subdir));
zip.Comment = "For testing purposes, please extract to: " + DesiredunpackDir;
if (Passwords[k] != null) zip.Comment += String.Format("\r\n\r\nThe password for all entries is: {0}\n", Passwords[k]);
var sfxOptions = new SelfExtractorSaveOptions
{
Flavor = Ionic.Zip.SelfExtractorFlavor.WinFormsApplication,
// workitem 12608
SfxExeWindowTitle = "Custom SFX Title " + DateTime.Now.ToString("G"),
DefaultExtractDirectory = DesiredunpackDir
};
zip.SaveSelfExtractor(exeFileToCreate, sfxOptions);
}
// run the self-extracting EXE we just created
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(exeFileToCreate);
psi.Arguments = DesiredunpackDir;
psi.WorkingDirectory = TopLevelDir;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
System.Diagnostics.Process process = System.Diagnostics.Process.Start(psi);
process.WaitForExit();
// now, compare the output in TargetDirectory with the original
string DirToCheck = Path.Combine(DesiredunpackDir, String.Format("A{0}", k));
// verify the checksum of each file matches with its brother
var fileList = Directory.GetFiles(DirToCheck);
Assert.AreEqual<Int32>(checksums.Keys.Count, fileList.Length, "Trial {0}: Inconsistent results.", k);
foreach (string fname in fileList)
{
string expectedCheckString = checksums[fname.Replace(String.Format("\\unpack{0}", k), "")];
string actualCheckString = TestUtilities.CheckSumToString(TestUtilities.ComputeChecksum(fname));
Assert.AreEqual<String>(expectedCheckString, actualCheckString, "Trial {0}: Unexpected checksum on extracted filesystem file ({1}).", k, fname);
}
}
}
示例13: SFX_Console
public void SFX_Console()
{
string exeFileToCreate = Path.Combine(TopLevelDir, "SFX_Console.exe");
string unpackDir = Path.Combine(TopLevelDir, "unpack");
string readmeString = "Hey there! This zipfile entry was created directly from a string in application code.";
int entriesAdded = 0;
String filename = null;
string Subdir = Path.Combine(TopLevelDir, "A");
Directory.CreateDirectory(Subdir);
var checksums = new Dictionary<string, string>();
int fileCount = _rnd.Next(10) + 10;
for (int j = 0; j < fileCount; j++)
{
filename = Path.Combine(Subdir, String.Format("file{0:D3}.txt", j));
TestUtilities.CreateAndFillFileText(filename, _rnd.Next(34000) + 5000);
entriesAdded++;
var chk = TestUtilities.ComputeChecksum(filename);
checksums.Add(filename, TestUtilities.CheckSumToString(chk));
}
using (ZipFile zip = new ZipFile())
{
zip.AddDirectory(Subdir, Path.GetFileName(Subdir));
zip.Comment = "This will be embedded into a self-extracting exe";
MemoryStream ms1 = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(readmeString));
zip.AddEntry("Readme.txt", ms1);
var sfxOptions = new SelfExtractorSaveOptions
{
Flavor = Ionic.Zip.SelfExtractorFlavor.ConsoleApplication,
DefaultExtractDirectory = unpackDir
};
zip.SaveSelfExtractor(exeFileToCreate, sfxOptions);
}
var psi = new System.Diagnostics.ProcessStartInfo(exeFileToCreate);
psi.WorkingDirectory = TopLevelDir;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
System.Diagnostics.Process process = System.Diagnostics.Process.Start(psi);
process.WaitForExit();
// now, compare the output in unpackDir with the original
string DirToCheck = Path.Combine(unpackDir, "A");
// verify the checksum of each file matches with its brother
foreach (string fname in Directory.GetFiles(DirToCheck))
{
string originalName = fname.Replace("\\unpack", "");
if (checksums.ContainsKey(originalName))
{
string expectedCheckString = checksums[originalName];
string actualCheckString = TestUtilities.CheckSumToString(TestUtilities.ComputeChecksum(fname));
Assert.AreEqual<String>(expectedCheckString, actualCheckString, "Unexpected checksum on extracted filesystem file ({0}).", fname);
}
else
Assert.AreEqual<string>("Readme.txt", originalName);
}
}
示例14: SFX_Update
private void SFX_Update(SelfExtractorFlavor flavor)
{
string sfxFileToCreate = Path.Combine(TopLevelDir,
String.Format("SFX_Update{0}.exe",
flavor.ToString()));
string unpackDir = Path.Combine(TopLevelDir, "unpack");
if (Directory.Exists(unpackDir))
Directory.Delete(unpackDir, true);
string readmeString = "Hey there! This zipfile entry was created directly from a string in application code.";
// create a file and compute the checksum
string Subdir = Path.Combine(TopLevelDir, "files");
Directory.CreateDirectory(Subdir);
var checksums = new Dictionary<string, string>();
string filename = Path.Combine(Subdir, "file1.txt");
TestUtilities.CreateAndFillFileText(filename, _rnd.Next(34000) + 5000);
var chk = TestUtilities.ComputeChecksum(filename);
checksums.Add(filename.Replace(TopLevelDir + "\\", "").Replace('\\', '/'), TestUtilities.CheckSumToString(chk));
// create the SFX
using (ZipFile zip1 = new ZipFile())
{
zip1.AddFile(filename, Path.GetFileName(Subdir));
zip1.Comment = "This will be embedded into a self-extracting exe";
MemoryStream ms1 = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(readmeString));
zip1.AddEntry("Readme.txt", ms1);
var sfxOptions = new SelfExtractorSaveOptions
{
Flavor = flavor,
Quiet = true,
DefaultExtractDirectory = unpackDir
};
zip1.SaveSelfExtractor(sfxFileToCreate, sfxOptions);
}
// verify count
Assert.AreEqual<int>(TestUtilities.CountEntries(sfxFileToCreate), 2, "The Zip file has the wrong number of entries.");
// create another file
filename = Path.Combine(Subdir, "file2.txt");
TestUtilities.CreateAndFillFileText(filename, _rnd.Next(34000) + 5000);
chk = TestUtilities.ComputeChecksum(filename);
checksums.Add(filename.Replace(TopLevelDir + "\\", "").Replace('\\', '/'), TestUtilities.CheckSumToString(chk));
string password = "ABCDEFG";
// update the SFX
using (ZipFile zip1 = ZipFile.Read(sfxFileToCreate))
{
zip1.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
zip1.Encryption = EncryptionAlgorithm.WinZipAes256;
zip1.Comment = "The password is: " + password;
zip1.Password = password;
zip1.AddFile(filename, Path.GetFileName(Subdir));
var sfxOptions = new SelfExtractorSaveOptions
{
Flavor = flavor,
Quiet = true,
DefaultExtractDirectory = unpackDir
};
zip1.SaveSelfExtractor(sfxFileToCreate, sfxOptions);
}
// verify count
Assert.AreEqual<int>(TestUtilities.CountEntries(sfxFileToCreate), 3, "The Zip file has the wrong number of entries.");
// read the SFX
TestContext.WriteLine("---------------Reading {0}...", sfxFileToCreate);
using (ZipFile zip2 = ZipFile.Read(sfxFileToCreate))
{
zip2.Password = password;
//string extractDir = String.Format("extract{0}", j);
foreach (var e in zip2)
{
TestContext.WriteLine(" Entry: {0} c({1}) u({2})", e.FileName, e.CompressedSize, e.UncompressedSize);
e.Extract(unpackDir);
if (!e.IsDirectory)
{
if (checksums.ContainsKey(e.FileName))
{
filename = Path.Combine(unpackDir, e.FileName);
string actualCheckString = TestUtilities.CheckSumToString(TestUtilities.ComputeChecksum(filename));
Assert.AreEqual<string>(checksums[e.FileName], actualCheckString, "Checksums for ({1}) do not match.", e.FileName);
//TestContext.WriteLine(" Checksums match ({0}).\n", actualCheckString);
}
else
{
Assert.AreEqual<string>("Readme.txt", e.FileName);
}
}
}
}
int N = (flavor == SelfExtractorFlavor.ConsoleApplication) ? 2 : 1;
for (int j = 0; j < N; j++)
{
// run the SFX
TestContext.WriteLine("Running the SFX... ");
var psi = new System.Diagnostics.ProcessStartInfo(sfxFileToCreate);
//.........这里部分代码省略.........
示例15: ZipFiles
//.........这里部分代码省略.........
zip.UseZip64WhenSaving = Zip64 ? Zip64Option.AsNecessary: Zip64Option.Never;
if (!string.IsNullOrEmpty(Password))
zip.Password = Password;
if (string.Equals(Encryption, "PkzipWeak", StringComparison.OrdinalIgnoreCase))
zip.Encryption = EncryptionAlgorithm.PkzipWeak;
else if (string.Equals(Encryption, "WinZipAes128", StringComparison.OrdinalIgnoreCase))
zip.Encryption = EncryptionAlgorithm.WinZipAes128;
else if (string.Equals(Encryption, "WinZipAes256", StringComparison.OrdinalIgnoreCase))
zip.Encryption = EncryptionAlgorithm.WinZipAes256;
else
zip.Encryption = EncryptionAlgorithm.None;
if (!string.IsNullOrEmpty(Comment))
zip.Comment = Comment;
foreach (ITaskItem fileItem in Files)
{
string name = fileItem.ItemSpec;
string directoryPathInArchive;
// clean up name
if (Flatten)
directoryPathInArchive = string.Empty;
else if (!string.IsNullOrEmpty(WorkingDirectory))
directoryPathInArchive = GetPath(name, WorkingDirectory);
else
directoryPathInArchive = null;
if (!File.Exists(name))
{
// maybe a directory
if (Directory.Exists(name))
{
var directoryEntry = zip.AddDirectory(name, directoryPathInArchive);
if (!Quiet)
Log.LogMessage(Resources.ZipAdded, directoryEntry.FileName);
continue;
}
Log.LogWarning(Resources.FileNotFound, name);
continue;
}
//remove file name
if (!string.IsNullOrEmpty(directoryPathInArchive)
&& Path.GetFileName(directoryPathInArchive) == Path.GetFileName(name))
directoryPathInArchive = Path.GetDirectoryName(directoryPathInArchive);
var entry = zip.AddFile(name, directoryPathInArchive);
if (!Quiet)
Log.LogMessage(Resources.ZipAdded, entry.FileName);
}
if (SelfExtracting)
{
var options = new SelfExtractorSaveOptions
{
AdditionalCompilerSwitches = AdditionalCompilerSwitches,
Copyright = Copyright,
DefaultExtractDirectory = DefaultExtractDirectory,
Description = Description,
ExtractExistingFile = (ExtractExistingFileAction) ExtractExistingFileAction,
Flavor = ConsoleSelfExtractor
? SelfExtractorFlavor.ConsoleApplication
: SelfExtractorFlavor.WinFormsApplication,
IconFile = IconFile,
PostExtractCommandLine = PostExtractCommandLine,
ProductName = ProductName,
ProductVersion = ProductVersion,
Quiet = QuietExtraction,
RemoveUnpackedFilesAfterExecute = RemoveUnpackedFilesAfterExecute,
SfxExeWindowTitle = SelfExtractingArchiveWindowTitle
};
if (!string.IsNullOrWhiteSpace(FileVersion))
{
options.FileVersion = new System.Version(FileVersion);
}
zip.SaveSelfExtractor(ZipFileName, options);
}
else
{
zip.Save(ZipFileName);
}
Log.LogMessage(Resources.ZipSuccessfully, ZipFileName);
}
}
catch (Exception exc)
{
Log.LogErrorFromException(exc);
return false;
}
return true;
}