npo*_*aka 42 .net zip batch-file jscript
我知道这里有很多类似的问题,但我对答案(甚至是问题)都不满意.
主要目标是兼容性 - 它应该适用于最广泛的Windows机器(包括XP,Vista,Win2003 - 它们共同占据了大约20%的Windows共享),并且生成的文件应该可以在Unix/Mac机器上使用(所以标准存档/压缩格式是优选的).
选项有哪些:
npo*_*aka 58
以下是答案:
1.使用"纯"批处理脚本来压缩/解压缩文件.
这可能要归功于Frank Westlake的ZIP.CMD 和UNZIP.CMD(需要管理员权限和要求FSUTIL和CERTUTIL).对于Win2003和WinXP,它将需要 安装2003 Admin Tool PackCERTUTIL.注意ZIP.CMD语法是向后的:
ZIP.CMD destination.zip source.file
Run Code Online (Sandbox Code Playgroud)
它只能压缩单个文件.
2.使用Shell.Application
我花了一些时间来创建一个单独的jscript/batch混合脚本,用于拉链/解压缩文件和目录(以及更多功能)的常见用法.这是一个链接(它变得太大了,无法在答案中发布).可以直接与其.bat扩展名一起使用,也不会创建任何临时文件.我希望帮助信息足够描述如何使用它.
一些例子:
// unzip content of a zip to given folder.content of the zip will be not preserved (-keep no).Destination will be not overwritten (-force no)
call zipjs.bat unzip -source C:\myDir\myZip.zip -destination C:\MyDir -keep no -force no
// lists content of a zip file and full paths will be printed (-flat yes)
call zipjs.bat list -source C:\myZip.zip\inZipDir -flat yes
// lists content of a zip file and the content will be list as a tree (-flat no)
call zipjs.bat list -source C:\myZip.zip -flat no
// prints uncompressed size in bytes
zipjs.bat getSize -source C:\myZip.zip
// zips content of folder without the folder itself
call zipjs.bat zipDirItems -source C:\myDir\ -destination C:\MyZip.zip -keep yes -force no
// zips file or a folder (with the folder itslelf)
call zipjs.bat zipItem -source C:\myDir\myFile.txt -destination C:\MyZip.zip -keep yes -force no
// unzips only part of the zip with given path inside
call zipjs.bat unZipItem -source C:\myDir\myZip.zip\InzipDir\InzipFile -destination C:\OtherDir -keep no -force yes
call zipjs.bat unZipItem -source C:\myDir\myZip.zip\InzipDir -destination C:\OtherDir
// adds content to a zip file
call zipjs.bat addToZip -source C:\some_file -destination C:\myDir\myZip.zip\InzipDir -keep no
call zipjs.bat addToZip -source C:\some_file -destination C:\myDir\myZip.zip
Run Code Online (Sandbox Code Playgroud)
压缩过程中的一些已知问题:
该脚本检测是否弹出错误消息并停止执行并通知可能的原因.此时我无法检测弹出窗口中的文本并提供失败的确切原因.
3. Makecab.
压缩文件很简单 - makecab file.txt "file.cab".最终可以增加MaxCabinetSize.压缩文件夹需要为每个(子)目录和其中的文件使用DestinationDir指令(具有相对路径).这是一个脚本:
;@echo off
;;;;; rem start of the batch part ;;;;;
;
;for %%a in (/h /help -h -help) do (
; if /I "%~1" equ "%%~a" if "%~2" equ "" (
; echo compressing directory to cab file
; echo Usage:
; echo(
; echo %~nx0 "directory" "cabfile"
; echo(
; echo to uncompress use:
; echo EXPAND cabfile -F:* .
; echo(
; echo Example:
; echo(
; echo %~nx0 "c:\directory\logs" "logs"
; exit /b 0
; )
; )
;
; if "%~2" EQU "" (
; echo invalid arguments.For help use:
; echo %~nx0 /h
; exit /b 1
;)
;
; set "dir_to_cab=%~f1"
;
; set "path_to_dir=%~pn1"
; set "dir_name=%~n1"
; set "drive_of_dir=%~d1"
; set "cab_file=%~2"
;
; if not exist %dir_to_cab%\ (
; echo no valid directory passed
; exit /b 1
;)
;
;break>"%tmp%\makecab.dir.ddf"
;
;setlocal enableDelayedExpansion
;for /d /r "%dir_to_cab%" %%a in (*) do (
;
; set "_dir=%%~pna"
; set "destdir=%dir_name%!_dir:%path_to_dir%=!"
; (echo(.Set DestinationDir=!destdir!>>"%tmp%\makecab.dir.ddf")
; for %%# in ("%%a\*") do (
; (echo("%%~f#" /inf=no>>"%tmp%\makecab.dir.ddf")
; )
;)
;(echo(.Set DestinationDir=!dir_name!>>"%tmp%\makecab.dir.ddf")
; for %%# in ("%~f1\*") do (
;
; (echo("%%~f#" /inf=no>>"%tmp%\makecab.dir.ddf")
; )
;makecab /F "%~f0" /f "%tmp%\makecab.dir.ddf" /d DiskDirectory1=%cd% /d CabinetNameTemplate=%cab_file%.cab
;rem del /q /f "%tmp%\makecab.dir.ddf"
;exit /b %errorlevel%
;;
;;;; rem end of the batch part ;;;;;
;;;; directives part ;;;;;
;;
.New Cabinet
.set GenerateInf=OFF
.Set Cabinet=ON
.Set Compress=ON
.Set UniqueFiles=ON
.Set MaxDiskSize=1215751680;
.set RptFileName=nul
.set InfFileName=nul
.set MaxErrors=1
;;
;;;; end of directives part ;;;;;
Run Code Online (Sandbox Code Playgroud)
对于解压缩EXPAND cabfile -F:* .可以使用.对于Unix中的提取,可以使用cabextract或7zip.
4. .NET和GZipStream
我更喜欢Jscript.net,因为它允许与.bat进行整齐的杂交(没有有毒输出,没有临时文件).Jscript不允许将对象的引用传递给函数,所以我发现让它工作的唯一方法是逐字节读/写文件(所以我想这不是最快的方法 - 如何进行缓冲读/写?)再次只能用于单个文件.
@if (@X)==(@Y) @end /* JScript comment
@echo off
setlocal
for /f "tokens=* delims=" %%v in ('dir /b /s /a:-d /o:-n "%SystemRoot%\Microsoft.NET\Framework\*jsc.exe"') do (
set "jsc=%%v"
)
if not exist "%~n0.exe" (
"%jsc%" /nologo /out:"%~n0.exe" "%~dpsfnx0"
)
%~n0.exe %*
endlocal & exit /b %errorlevel%
*/
import System;
import System.Collections.Generic;
import System.IO;
import System.IO.Compression;
function CompressFile(source,destination){
var sourceFile=File.OpenRead(source);
var destinationFile=File.Create(destination);
var output = new GZipStream(destinationFile,CompressionMode.Compress);
Console.WriteLine("Compressing {0} to {1}.", sourceFile.Name,destinationFile.Name, false);
var byteR = sourceFile.ReadByte();
while(byteR !=- 1){
output.WriteByte(byteR);
byteR = sourceFile.ReadByte();
}
sourceFile.Close();
output.Flush();
output.Close();
destinationFile.Close();
}
function UncompressFile(source,destination){
var sourceFile=File.OpenRead(source);
var destinationFile=File.Create(destination);
var input = new GZipStream(sourceFile,
CompressionMode.Decompress, false);
Console.WriteLine("Decompressing {0} to {1}.", sourceFile.Name,
destinationFile.Name);
var byteR=input.ReadByte();
while(byteR !== -1){
destinationFile.WriteByte(byteR);
byteR=input.ReadByte();
}
destinationFile.Close();
input.Close();
}
var arguments:String[] = Environment.GetCommandLineArgs();
function printHelp(){
Console.WriteLine("Compress and uncompress gzip files:");
Console.WriteLine("Compress:");
Console.WriteLine(arguments[0]+" -c source destination");
Console.WriteLine("Uncompress:");
Console.WriteLine(arguments[0]+" -u source destination");
}
if (arguments.length!=4){
Console.WriteLine("Wrong arguments");
printHelp();
Environment.Exit(1);
}
switch (arguments[1]){
case "-c":
CompressFile(arguments[2],arguments[3]);
break;
case "-u":
UncompressFile(arguments[2],arguments[3]);
break;
default:
Console.WriteLine("Wrong arguments");
printHelp();
Environment.Exit(1);
}
Run Code Online (Sandbox Code Playgroud)
惊人的解决方案!
Makecab解决方案存在一些问题,因此,这里是一个固定版本,可以解决在使用带空格的目录时解决的问题。
;@echo off
;;;;; rem start of the batch part ;;;;;
;
;for %%a in (/h /help -h -help) do (
; if /I "%~1" equ "%%~a" if "%~2" equ "" (
; echo compressing directory to cab file
; echo Usage:
; echo(
; echo %~nx0 "directory" "cabfile"
; echo(
; echo to uncompress use:
; echo EXPAND cabfile -F:* .
; echo(
; echo Example:
; echo(
; echo %~nx0 "c:\directory\logs" "logs"
; exit /b 0
; )
; )
;
; if "%~2" EQU "" (
; echo invalid arguments.For help use:
; echo %~nx0 /h
; exit /b 1
;)
;
; set "dir_to_cab=%~f1"
;
; set "path_to_dir=%~pn1"
; set "dir_name=%~n1"
; set "drive_of_dir=%~d1"
; set "cab_file=%~2"
;
; if not exist "%dir_to_cab%\" (
; echo no valid directory passed
; exit /b 1
;)
;
;break>"%tmp%\makecab.dir.ddf"
;
;setlocal enableDelayedExpansion
;for /d /r "%dir_to_cab%" %%a in (*) do (
;
; set "_dir=%%~pna"
; set "destdir=%dir_name%!_dir:%path_to_dir%=!"
; (echo(.Set DestinationDir=!destdir!>>"%tmp%\makecab.dir.ddf")
; for %%# in ("%%a\*") do (
; (echo("%%~f#" /inf=no>>"%tmp%\makecab.dir.ddf")
; )
;)
;(echo(.Set DestinationDir=!dir_name!>>"%tmp%\makecab.dir.ddf")
; for %%# in ("%~f1\*") do (
;
; (echo("%%~f#" /inf=no>>"%tmp%\makecab.dir.ddf")
; )
;makecab /F "%~f0" /f "%tmp%\makecab.dir.ddf" /d DiskDirectory1="%cd%" /d CabinetNameTemplate=%cab_file%.cab
;rem del /q /f "%tmp%\makecab.dir.ddf"
;exit /b %errorlevel%
;;
;;;; rem end of the batch part ;;;;;
;;;; directives part ;;;;;
;;
.New Cabinet
.set GenerateInf=OFF
.Set Cabinet=ON
.Set Compress=ON
.Set UniqueFiles=ON
.Set MaxDiskSize=1215751680;
.set RptFileName=nul
.set InfFileName=nul
.set MaxErrors=1
;;
;;;; end of directives part ;;;;;
Run Code Online (Sandbox Code Playgroud)
使用Compress-Archive和Expand-Archive的 powershell 的一些示例:
//zipping folder or file:
powershell "Compress-Archive -Path """C:\some_folder""" -DestinationPath """zippedFolder.zip""""
//unzipping folder:
powershell "Expand-Archive -Path """Draftv2.Zip""" -DestinationPath """C:\Reference""""
Run Code Online (Sandbox Code Playgroud)
与当前支持的 Windows 版本一样,默认情况下会安装这些 cmd-let。
使用 powershell 的另一种方法
//zip directory
powershell "Add-Type -Assembly """System.IO.Compression.FileSystem""" ;[System.IO.Compression.ZipFile]::CreateFromDirectory("""C:\some_dir""", """some.zip""");"
//unzip directory
powershell "Add-Type -Assembly "System.IO.Compression.FileSystem" ;[System.IO.Compression.ZipFile]::ExtractToDirectory("""yourfile.zip""", """c:\your\destination""");"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
73303 次 |
| 最近记录: |