sz.cs
来自「全功能c#编译器」· CS 代码 · 共 1,131 行 · 第 1/3 页
CS
1,131 行
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 && operation == Operation.Create) {
string checkPath = (string)fileSpecs[0];
int deviceCheck = checkPath.IndexOf(':');
if (checkPath.IndexOfAny(Path.InvalidPathChars) >= 0
|| 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;
}
/// <summary>
/// Show encoding/locale information
/// </summary>
void ShowEnvironment()
{
seenHelp = true;
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);
}
/// <summary>
/// Display version information
/// </summary>
void ShowVersion() {
seenHelp = true;
Console.Out.WriteLine("SharpZip Archiver v0.34 Copyright 2004 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"
);
}
}
}
/// <summary>
/// Show help on possible options and arguments
/// </summary>
void ShowHelp()
{
if (seenHelp == true) {
return;
}
seenHelp = true;
ShowVersion();
Console.Out.WriteLine("usage sz {options} archive files");
Console.Out.WriteLine("");
Console.Out.WriteLine("Options:");
Console.Out.WriteLine("-?, --help Show this help");
Console.Out.WriteLine("-c --create Create new archive");
Console.Out.WriteLine("-v List archive contents (default)");
Console.Out.WriteLine("--list List archive contents extended format");
Console.Out.WriteLine("-x{=dir}, --extract{=dir} Extract archive contents to dir(default .)");
Console.Out.WriteLine("--extractdir=path Set extract directory (default .)");
Console.Out.WriteLine("--info Show current environment information" );
Console.Out.WriteLine("--store Store entries (default=deflate)");
Console.Out.WriteLine("--version Show version information");
Console.Out.WriteLine("--emptydirs Create entries for empty directories");
Console.Out.WriteLine("--encoding=codepage|name Set code page for encoding by name or number");
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("-p Store relative path info");
Console.Out.WriteLine("-r Recurse sub-folders");
Console.Out.WriteLine("-q Quiet mode");
Console.Out.WriteLine("-s=password Set archive password");
Console.Out.WriteLine("");
}
///<summary>
/// Calculate compression ratio as a percentage
/// Doesnt allow for expansion (ratio > 100) as the resulting strings can get huge easily
/// </summary>
int GetCompressionRatio(long packedSize, long unpackedSize)
{
int result = 0;
if (unpackedSize > 0 && unpackedSize >= packedSize) {
result = (int) Math.Round((1.0 - ((double)packedSize / (double)unpackedSize)) * 100.0);
}
return result;
}
/// <summary>
/// List zip file contents using stream
/// </summary>
/// <param name="fileName">File to list contents of</param>
void ListZip(string fileName) {
try
{
// TODO for asian/non-latin/non-proportional fonts string lengths dont work so output wont line up
const string headerTitles = "Name Length Ratio Size Date & time CRC-32";
const string headerUnderline = "--------------- ---------- ----- ---------- ------------------- --------";
FileInfo fileInfo = new FileInfo(fileName);
if (fileInfo.Exists == false) {
Console.Error.WriteLine("No such file exists {0}", fileName);
return;
}
Console.Out.WriteLine(fileName);
using (FileStream fileStream = File.OpenRead(fileName)) {
using (ZipInputStream stream = new ZipInputStream(fileStream)) {
if (password != null && password.Length > 0)
stream.Password = password;
int entryCount = 0;
long totalSize = 0;
ZipEntry theEntry;
while ((theEntry = stream.GetNextEntry()) != null) {
if (entryCount == 0) {
Console.Out.WriteLine(headerTitles);
Console.Out.WriteLine(headerUnderline);
}
++entryCount;
int ratio = GetCompressionRatio(theEntry.CompressedSize, theEntry.Size);
totalSize += theEntry.Size;
if (theEntry.Name.Length > 15) {
Console.Out.WriteLine(theEntry.Name);
Console.Out.WriteLine(
"{0,-15} {1,10:0} {2,3}% {3,10:0} {4,10:d} {4:hh:mm:ss} {5,8:x}",
"", theEntry.Size, ratio, theEntry.CompressedSize, theEntry.DateTime, theEntry.Crc);
} else {
Console.Out.WriteLine(
"{0,-15} {1,10:0} {2,3}% {3,10:0} {4,10:d} {4:hh:mm:ss} {5,8:x}",
theEntry.Name, theEntry.Size, ratio, theEntry.CompressedSize, theEntry.DateTime, theEntry.Crc);
}
}
if (entryCount == 0) {
Console.Out.WriteLine("Archive is empty!");
} else {
Console.Out.WriteLine(headerUnderline);
Console.Out.WriteLine(
"{0,-15} {1,10:0} {2,3}% {3,10:0} {4,10:d} {4:hh:mm:ss}",
entryCount.ToString() + " entries", totalSize, GetCompressionRatio(fileInfo.Length, totalSize), fileInfo.Length, fileInfo.LastWriteTime);
}
}
}
}
catch(Exception exception)
{
Console.Error.WriteLine("Exception during list operation: {0}", exception.Message);
}
}
string InterpretExternalAttributes(int os, int attributes)
{
string result = "";
if (os == 0)
{
if ((attributes & 0x10) != 0)
result = result + "D";
else
result = result + "-";
if ((attributes & 0x08) != 0)
result = result + "V";
else
result = result + "-";
if ((attributes & 0x01) != 0)
result = result + "r";
else
result = result + "-";
if ((attributes & 0x20) != 0)
result = result + "a";
else
result = result + "-";
if ((attributes & 0x04) != 0)
result = result + "s";
else
result = result + "-";
if ((attributes & 0x02) != 0)
result = result + "h";
else
result = result + "-";
}
return result;
}
/// <summary>
/// List zip file contents using ZipFile class
/// </summary>
/// <param name="fileName">File to list contents of</param>
void ListZipViaZipFile(string fileName) {
try
{
const string headerTitles = "Name Length Ratio Size Date & time CRC-32 Attr";
const string headerUnderline = "------------ ---------- ----- ---------- ------------------- -------- ------";
FileInfo fileInfo = new FileInfo(fileName);
if (fileInfo.Exists == false) {
Console.Error.WriteLine("No such file exists {0}", fileName);
return;
}
Console.Out.WriteLine(fileName);
ZipFile zipFile = new ZipFile(fileName);
int entryCount = 0;
long totalSize = 0;
foreach (ZipEntry theEntry in zipFile) {
if (entryCount == 0) {
Console.Out.WriteLine(headerTitles);
Console.Out.WriteLine(headerUnderline);
}
++entryCount;
int ratio = GetCompressionRatio(theEntry.CompressedSize, theEntry.Size);
totalSize += theEntry.Size;
if (theEntry.Name.Length > 12) {
Console.Out.WriteLine(theEntry.Name);
Console.Out.WriteLine(
"{0,-12} {1,10:0} {2,3}% {3,10:0} {4,10:d} {4:hh:mm:ss} {5,8:x} {6,4}",
"", theEntry.Size, ratio, theEntry.CompressedSize, theEntry.DateTime, theEntry.Crc,
InterpretExternalAttributes(theEntry.HostSystem, theEntry.ExternalFileAttributes));
} else {
Console.Out.WriteLine(
"{0,-12} {1,10:0} {2,3}% {3,10:0} {4,10:d} {4:hh:mm:ss} {5,8:x} {6,4}",
theEntry.Name, theEntry.Size, ratio, theEntry.CompressedSize, theEntry.DateTime, theEntry.Crc,
InterpretExternalAttributes(theEntry.HostSystem, theEntry.ExternalFileAttributes));
}
}
if (entryCount == 0) {
Console.Out.WriteLine("Archive is empty!");
} else {
Console.Out.WriteLine(headerUnderline);
Console.Out.WriteLine(
"{0,-12} {1,10:0} {2,3}% {3,10:0} {4,10:d} {4:hh:mm:ss}",
entryCount.ToString() + " entries", totalSize, GetCompressionRatio(fileInfo.Length, totalSize), fileInfo.Length, fileInfo.LastWriteTime);
}
}
catch(Exception exception)
{
Console.Error.WriteLine("Exception during list operation: {0}", exception.Message);
}
}
/// <summary>
/// Execute List operation
/// Currently only Zip files are supported
/// </summary>
/// <param name="fileSpecs">Files to list</param>
void List(ArrayList fileSpecs)
{
foreach (string spec in fileSpecs) {
string [] names;
string pathName = Path.GetDirectoryName(spec);
if (pathName == null || pathName.Length == 0) {
pathName = @".\";
}
names = Directory.GetFiles(pathName, Path.GetFileName(spec));
if (names.Length == 0) {
Console.Error.WriteLine("No files found matching {0}", spec);
}
else {
foreach (string file in names) {
if (useZipFileWhenListing) {
ListZipViaZipFile(file);
} else {
ListZip(file);
}
Console.Out.WriteLine("");
}
}
}
}
/// <summary>
/// 'Cook' a name making it acceptable as a zip entry name.
/// </summary>
/// <param name="name">name to cook</param>
/// <param name="stripPrefix">String to remove from front of name if present</param>
/// <param name="relativePath">Make names relative if true or absolute if false</param>
static public string CookZipEntryName(string name, string stripPrefix, bool relativePath)
{
#if TEST
Console.WriteLine("Cooking '{0}' prefix is '{1}'", name, stripPrefix);
#endif
if (name == null) {
return "";
}
if (stripPrefix != null && stripPrefix.Length > 0 && name.IndexOf(stripPrefix, 0) == 0) {
name = name.Substring(stripPrefix.Length);
}
if (Path.IsPathRooted(name) == true) {
// NOTE:
// for UNC names... \\machine\share\zoom\beet.txt gives \zoom\beet.txt
name = name.Substring(Path.GetPathRoot(name).Length);
#if TEST
Console.WriteLine("Removing root info {0}", name);
#endif
}
name = name.Replace(@"\", "/");
if (relativePath == true) {
if (name.Length > 0 && (name[0] == Path.AltDirectorySeparatorChar || name[0] == Path.DirectorySeparatorChar)) {
name = name.Remove(0, 1);
}
} else {
if (name.Length > 0 && name[0] != Path.AltDirectorySeparatorChar && name[0] != Path.DirectorySeparatorChar) {
name = name.Insert(0, "/");
}
}
#if TEST
Console.WriteLine("Cooked value '{0}'", name);
#endif
return name;
}
/// <summary>
/// Make string into something acceptable as an entry name
/// </summary>
/// <param name="name">Name to 'cook'</param>
string CookZipEntryName(string name)
{
return CookZipEntryName(name, removablePathPrefix, relativePathInfo);
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?