📄 zf.cs
字号:
//------------------------------------------------------------------------------
//
// zf - A command line archiver using the ZipFile class from SharpZipLib
// for compression
//
// Copyright 2006 John Reilly
//
//------------------------------------------------------------------------------
// Version History
// 1 Initial version ported from sz sample. Some stuff is not used or commented still
// 2 Display files during extract. --env Now shows .NET version information.
// 3 Add usezip64 option as a testing aid.
using System;
using System.IO;
using System.Collections;
using System.Text;
using System.Globalization;
using System.Diagnostics;
using System.Reflection;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip.Compression;
namespace SharpZip
{
/// <summary>
/// A command line archiver using the ZipFile class from SharpZipLib compression library
/// </summary>
public class ZipFileArchiver
{
#region Enumerations
/// <summary>
/// Options for handling overwriting of files.
/// </summary>
enum Overwrite
{
Prompt,
Never,
Always
}
/// <summary>
/// Kinds of thing we know how to do
/// </summary>
enum Operation
{
Create, // add files to new archive
Extract, // extract files from existing archive
List, // show contents of existing archive
Delete, // Delete from archive
Add, // Add to archive.
Test, // Test the archive for validity.
}
#endregion
#region Constructors
/// <summary>
/// Base constructor - initializes all fields to default values
/// </summary>
public ZipFileArchiver()
{
// Do nothing.
}
#endregion
#region Argument Parsing
/// <summary>
/// Parse command line arguments.
/// This is fairly flexible without using any custom classes. Arguments and options can appear
/// in any order and are case insensitive. Arguments for options are signalled with an '='
/// as in -demo=argument, sometimes the '=' can be omitted as well secretly.
/// Grouping of single character options is supported.
/// </summary>
/// <returns>
/// true if arguments are valid such that processing should continue
/// </returns>
bool SetArgs(string[] args)
{
bool result = true;
int argIndex = 0;
while (argIndex < args.Length)
{
if (args[argIndex][0] == '-' || args[argIndex][0] == '/')
{
string option = args[argIndex].Substring(1).ToLower();
string optArg = "";
int parameterIndex = option.IndexOf('=');
if (parameterIndex >= 0)
{
if (parameterIndex < option.Length - 1)
{
optArg = option.Substring(parameterIndex + 1);
}
option = option.Substring(0, parameterIndex);
}
#if OPTIONTEST
Console.WriteLine("args index [{0}] option [{1}] argument [{2}]", argIndex, option, optArg);
#endif
if (option.Length == 0)
{
System.Console.Error.WriteLine("Invalid argument (0}", args[argIndex]);
result = false;
}
else
{
int optionIndex = 0;
while (optionIndex < option.Length)
{
#if OPTIONTEST
Console.WriteLine("optionIndex {0}", optionIndex);
#endif
switch(option[optionIndex])
{
case '-': // long option
optionIndex = option.Length;
switch (option)
{
case "-add":
operation_ = Operation.Add;
break;
case "-create":
operation_ = Operation.Create;
break;
case "-list":
operation_ = Operation.List;
break;
case "-extract":
operation_ = Operation.Extract;
if (optArg.Length > 0)
{
targetOutputDirectory_ = optArg;
}
break;
case "-delete":
operation_ = Operation.Delete;
break;
case "-test":
operation_ = Operation.Test;
break;
case "-env":
ShowEnvironment();
break;
case "-emptydirs":
addEmptyDirectoryEntries_ = true;
break;
case "-data":
testData_ = true;
break;
case "-zip64":
if ( optArg.Length > 0 )
{
switch ( optArg )
{
case "on":
useZip64_ = UseZip64.On;
break;
case "off":
useZip64_ = UseZip64.Off;
break;
case "auto":
useZip64_ = UseZip64.Dynamic;
break;
}
}
break;
case "-encoding":
if (optArg.Length > 0)
{
if (IsNumeric(optArg))
{
try
{
int enc = int.Parse(optArg);
if (Encoding.GetEncoding(enc) != null)
{
#if OPTIONTEST
Console.WriteLine("Encoding set to {0}", enc);
#endif
ZipConstants.DefaultCodePage = enc;
}
else
{
result = false;
System.Console.Error.WriteLine("Invalid encoding " + args[argIndex]);
}
}
catch (Exception)
{
result = false;
System.Console.Error.WriteLine("Invalid encoding " + args[argIndex]);
}
}
else
{
try
{
ZipConstants.DefaultCodePage = Encoding.GetEncoding(optArg).CodePage;
}
catch (Exception)
{
result = false;
System.Console.Error.WriteLine("Invalid encoding " + args[argIndex]);
}
}
}
else
{
result = false;
System.Console.Error.WriteLine("Missing encoding parameter");
}
break;
case "-version":
ShowVersion();
break;
case "-help":
ShowHelp();
break;
case "-restore-dates":
restoreDateTime_ = true;
break;
default:
System.Console.Error.WriteLine("Invalid long argument " + args[argIndex]);
result = false;
break;
}
break;
case '?':
ShowHelp();
break;
case 's':
if (optionIndex != 0)
{
result = false;
System.Console.Error.WriteLine("-s cannot be in a group");
}
else
{
if (optArg.Length > 0)
{
password_ = optArg;
}
else if (option.Length > 1)
{
password_ = option.Substring(1);
}
else
{
System.Console.Error.WriteLine("Missing argument to " + args[argIndex]);
}
}
optionIndex = option.Length;
break;
case 't':
operation_ = Operation.Test;
break;
case 'c':
operation_ = Operation.Create;
break;
case 'e':
if (optionIndex != 0)
{
result = false;
System.Console.Error.WriteLine("-e cannot be in a group");
}
else
{
optionIndex = option.Length;
if (optArg.Length > 0)
{
try
{
compressionLevel_ = int.Parse(optArg);
}
catch (Exception)
{
System.Console.Error.WriteLine("Level invalid");
}
}
}
optionIndex = option.Length;
break;
case 'o':
optionIndex += 1;
overwriteFiles = optionIndex < option.Length ? (option[optionIndex] == '+') ? Overwrite.Always : Overwrite.Never : Overwrite.Never;
break;
case 'q':
silent_ = true;
if (overwriteFiles == Overwrite.Prompt)
{
overwriteFiles = Overwrite.Never;
}
break;
case 'r':
recursive_ = true;
break;
case 'v':
operation_ = Operation.List;
break;
case 'x':
if (optionIndex != 0)
{
result = false;
System.Console.Error.WriteLine("-x cannot be in a group");
}
else
{
operation_ = Operation.Extract;
if (optArg.Length > 0)
{
targetOutputDirectory_ = optArg;
}
}
optionIndex = option.Length;
break;
default:
System.Console.Error.WriteLine("Invalid argument: " + args[argIndex]);
result = false;
break;
}
++optionIndex;
}
}
}
else
{
#if OPTIONTEST
Console.WriteLine("file spec {0} = '{1}'", argIndex, args[argIndex]);
#endif
fileSpecs_.Add(args[argIndex]);
}
++argIndex;
}
if (fileSpecs_.Count > 0)
{
string checkPath = (string)fileSpecs_[0];
int deviceCheck = checkPath.IndexOf(':');
#if NET_VER_1
if (checkPath.IndexOfAny(Path.InvalidPathChars) >= 0
#else
if (checkPath.IndexOfAny(Path.GetInvalidPathChars()) >= 0
#endif
|| checkPath.IndexOf('*') >= 0 || checkPath.IndexOf('?') >= 0
|| ((deviceCheck >= 0) && (deviceCheck != 1)))
{
Console.WriteLine("There are invalid characters in the specified zip file name");
result = false;
}
}
return result && (fileSpecs_.Count > 0);
}
#endregion
#region Show - Help/Environment/Version
/// <summary>
/// Show encoding/locale information
/// </summary>
void ShowEnvironment()
{
seenHelp_ = true;
Console.Out.WriteLine("");
System.Console.Out.WriteLine(
"Current encoding is {0}, code page {1}, windows code page {2}",
System.Console.Out.Encoding.EncodingName,
System.Console.Out.Encoding.CodePage,
System.Console.Out.Encoding.WindowsCodePage);
System.Console.WriteLine("Default code page is {0}",
Encoding.Default.CodePage);
Console.WriteLine( "Current culture LCID 0x{0:X}, {1}", CultureInfo.CurrentCulture.LCID, CultureInfo.CurrentCulture.EnglishName);
Console.WriteLine( "Current thread OEM codepage {0}", System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.OEMCodePage);
Console.WriteLine( "Current thread Mac codepage {0}", System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.MacCodePage);
Console.WriteLine( "Current thread Ansi codepage {0}", System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ANSICodePage);
Console.WriteLine(".NET version {0}", Environment.Version);
}
/// <summary>
/// Display version information
/// </summary>
void ShowVersion()
{
seenHelp_ = true;
Console.Out.WriteLine("ZipFile Archiver v0.3 Copyright 2006 John Reilly");
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly assembly in assemblies)
{
if (assembly.GetName().Name == "ICSharpCode.SharpZipLib")
{
Console.Out.WriteLine("#ZipLib v{0} {1}", assembly.GetName().Version,
assembly.GlobalAssemblyCache == true ? "Running from GAC" : "Running from DLL"
);
}
}
Console.Out.WriteLine();
}
/// <summary>
/// Show help on possible options and arguments
/// </summary>
void ShowHelp()
{
if (seenHelp_ == true)
{
return;
}
seenHelp_ = true;
ShowVersion();
Console.Out.WriteLine("usage zf {options} archive files");
Console.Out.WriteLine("");
Console.Out.WriteLine("Options:");
Console.Out.WriteLine("--add Add files to archive");
Console.Out.WriteLine("--create Create new archive");
Console.Out.WriteLine("--data Test archive data"); Console.Out.WriteLine("--delete Delete files from archive");
Console.Out.WriteLine("--encoding=codepage|name Set code page for encoding by name or number");
Console.Out.WriteLine("--extract{=dir} Extract archive contents to dir(default .)");
Console.Out.WriteLine("--help Show this help");
Console.Out.WriteLine("--env Show current environment information" );
Console.Out.WriteLine("--list List archive contents extended format");
Console.Out.WriteLine("--test Test archive for validity");
Console.Out.WriteLine("--version Show version information");
Console.Out.WriteLine("-r Recurse sub-folders");
Console.Out.WriteLine("-s=password Set archive password");
Console.Out.WriteLine("--zip64=[on|off|auto] Zip64 extension handling to use");
/*
Console.Out.WriteLine("--store Store entries (default=deflate)");
Console.Out.WriteLine("--emptydirs Create entries for empty directories");
Console.Out.WriteLine("--restore-dates Restore dates on extraction");
Console.Out.WriteLine("-o+ Overwrite files without prompting");
Console.Out.WriteLine("-o- Never overwrite files");
Console.Out.WriteLine("-q Quiet mode");
*/
Console.Out.WriteLine("");
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -