📄 sz.cs
字号:
// SharpZipLibrary samples
// Copyright (c) 2007, AlphaSierraPapa
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this list
// of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// - Neither the name of the SharpDevelop team nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific prior written
// permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &AS IS& AND ANY EXPRESS
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
// IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Define test to add more detailed Console.WriteLine style information
// #define TEST
using System;
using System.IO;
using System.Collections;
using System.Text;
using System.Globalization;
using System.Diagnostics;
using System.Reflection;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
namespace SharpZip
{
/// <summary>
/// A command line archiver using the SharpZipLib compression library
/// </summary>
public class SharpZipArchiver {
/// <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.
}
#region Constructors
/// <summary>
/// Base constructor - initializes all fields to default values
/// </summary>
public SharpZipArchiver()
{
}
#endregion
/// <summary>
/// Interpret attributes based on the operating system they are from.
/// </summary>
/// <param name="operatingSystem">The operating system to base interpretation of attributes on.</param>
/// <param name="attributes">The external attributes.</param>
/// <returns>A string representation of the attributres passed.</returns>
static string InterpretExternalAttributes(int operatingSystem, int attributes)
{
string result = string.Empty;
if ((operatingSystem == 0) || (operatingSystem == 10))
{
// Directory
if ((attributes & 0x10) != 0)
result = result + "D";
else
result = result + "-";
// Volume
if ((attributes & 0x08) != 0)
result = result + "V";
else
result = result + "-";
// Read-only
if ((attributes & 0x01) != 0)
result = result + "r";
else
result = result + "-";
// Archive
if ((attributes & 0x20) != 0)
result = result + "a";
else
result = result + "-";
// System
if ((attributes & 0x04) != 0)
result = result + "s";
else
result = result + "-";
// Hidden
if ((attributes & 0x02) != 0)
result = result + "h";
else
result = result + "-";
// Device
if ((attributes & 0x4) != 0)
result = result + "d";
else
result = result + "-";
// OS is NTFS
if ( operatingSystem == 10 )
{
// Encrypted
if ( (attributes & 0x4000) != 0 ) {
result += "E";
}
else {
result += "-";
}
// Not content indexed
if ( (attributes & 0x2000) != 0 ) {
result += "n";
}
else {
result += "-";
}
// Offline
if ( (attributes & 0x1000) != 0 ) {
result += "O";
}
else {
result += "-";
}
// Compressed
if ( (attributes & 0x0800) != 0 ) {
result += "C";
}
else {
result += "-";
}
// Reparse point
if ( (attributes & 0x0400) != 0 ) {
result += "R";
}
else {
result += "-";
}
// Sparse
if ( (attributes & 0x0200) != 0 ) {
result += "S";
}
else {
result += "-";
}
// Temporary
if ( (attributes & 0x0100) != 0 ) {
result += "T";
}
else {
result += "-";
}
}
}
return result;
}
/// <summary>
/// Determine if string is numeric [0-9]+
/// </summary>
/// <param name="rhs">string to test</param>
/// <returns>true iff rhs is numeric</returns>
static bool IsNumeric(string rhs)
{
bool result;
if (rhs != null && rhs.Length > 0) {
result = true;
for (int i = 0; i < rhs.Length; ++i) {
if (!char.IsDigit(rhs[i])) {
result = false;
break;
}
}
} else {
result = false;
}
return result;
}
/// <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.
///
/// The actual arguments and their handling is however a grab bag of ad-hoc things and its a bit messy. Could be a
/// bit more rigorous about how things are done. Up side is almost anything is/can be allowed
/// </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 (option.Length == 0) {
System.Console.WriteLine("Invalid argument (0}", args[argIndex]);
result = false;
}
else {
int optionIndex = 0;
while (optionIndex < option.Length) {
switch(option[optionIndex]) {
case '-': // long option
optionIndex = option.Length;
switch (option) {
case "-abs":
relativePathInfo = false;
break;
case "-add":
operation = Operation.Add;
break;
case "-create":
operation = Operation.Create;
break;
case "-list":
operation = Operation.List;
useZipFileWhenListing = true;
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 "-info":
ShowEnvironment();
break;
case "-emptydirs":
addEmptyDirectoryEntries = true;
break;
case "-data":
testData = true;
break;
case "-extractdir":
if (optArg.Length > 0) {
targetOutputDirectory = optArg;
} else {
result = false;
System.Console.WriteLine("Invalid extractdir " + args[argIndex]);
}
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) {
ZipConstants.DefaultCodePage = enc;
} else {
result = false;
System.Console.WriteLine("Invalid encoding " + args[argIndex]);
}
}
catch (Exception) {
result = false;
System.Console.WriteLine("Invalid encoding " + args[argIndex]);
}
} else {
try {
ZipConstants.DefaultCodePage = Encoding.GetEncoding(optArg).CodePage;
}
catch (Exception) {
result = false;
System.Console.WriteLine("Invalid encoding " + args[argIndex]);
}
}
} else {
result = false;
System.Console.WriteLine("Missing encoding parameter");
}
break;
case "-store":
useZipStored = true;
break;
case "-deflate":
useZipStored = false;
break;
case "-version":
ShowVersion();
break;
case "-help":
ShowHelp();
break;
#if !NETCF
case "-restore-dates":
restoreDateTime = true;
break;
#endif
default:
System.Console.WriteLine("Invalid long argument " + args[argIndex]);
result = false;
break;
}
break;
case '?':
ShowHelp();
break;
case 's':
if (optionIndex != 0) {
result = false;
System.Console.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.WriteLine("Missing argument to " + args[argIndex]);
}
}
optionIndex = option.Length;
break;
case 'c':
operation = Operation.Create;
break;
case 'l':
if (optionIndex != 0) {
result = false;
System.Console.WriteLine("-l cannot be in a group");
} else {
optionIndex = option.Length;
if (optArg.Length > 0) {
try {
compressionLevel = int.Parse(optArg);
}
catch (Exception) {
System.Console.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 'p':
relativePathInfo = true;
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.WriteLine("-x cannot be in a group");
} else {
operation = Operation.Extract;
if (optArg.Length > 0) {
targetOutputDirectory = optArg;
}
}
optionIndex = option.Length;
break;
default:
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -