C 壓縮檔案

2021-09-07 07:22:32 字數 3266 閱讀 8422

最近悟出來乙個道理,在這兒分享給大家:學歷代表你的過去,能力代表你的現在,學習代表你的將來。

十年河東十年河西,莫欺少年窮。

學無止境,精益求精

上一節講述了c# webapi傳參之post請求-ajax

本節**c#壓縮檔案的方法,直接上**

如下

public

class

ziputility

filestream streamtozip = new

filestream(filetozip, filemode.open, fileaccess.read);

filestream zipfile =file.create(zipedfile);

zipoutputstream zipstream = new

zipoutputstream(zipfile);

zipentry zipentry = new

zipentry(filetozip);

zipstream.putnextentry(zipentry);

zipstream.setlevel(compressionlevel);

byte buffer = new

byte

[blocksize];

int size = streamtozip.read(buffer, 0

, buffer.length);

zipstream.write(buffer,

0, size);

try }

catch

(exception ex)

zipstream.finish();

zipstream.close();

streamtozip.close();

gc.collect();

}//////

壓縮目錄(包括子目錄及所有檔案)

///

///要壓縮的根目錄

///儲存路徑

///壓縮程度,範圍0-9,數值越大,壓縮程式越高

public

void zipfilefromdirectory(string rootpath, string destinationpath, int

compresslevel)

*///

string rootmark = rootpath.substring(0, rootpath.lastindexof("\\") + 1);

//得到當前路徑的位置,以備壓縮時將所壓縮內容轉變成相對路徑。

string rootmark = rootpath + "

\\";//

得到當前路徑的位置,以備壓縮時將所壓縮內容轉變成相對路徑。

crc32 crc = new

crc32();

zipoutputstream outputstream = new

zipoutputstream(file.create(destinationpath));

outputstream.setlevel(compresslevel);

//0 - store only to 9 - means best compression

foreach (string file in

files)

this

.files.clear();

foreach (string emptypath in

paths)

this

.paths.clear();

outputstream.finish();

outputstream.close();

gc.collect();

}//////

取得目錄下所有檔案及資料夾,分別存入files及paths

///

///根目錄

private

void getalldirectories(string

rootpath)

string files =directory.getfiles(rootpath);

foreach (string file in

files)

if (subpaths.length == files.length && files.length == 0)//

如果是空目錄

}//////

解壓縮檔案(壓縮檔案中含有子目錄)

///

///待解壓縮的檔案路徑

///解壓縮到指定目錄

///解壓後的檔案列表

public list unzip(string zipfilepath, string

unzippath)

zipinputstream s = new

zipinputstream(file.openread(zipfilepath));

zipentry theentry;

while ((theentry = s.getnextentry()) != null

)

if (filename !=string.empty)

else

}streamwriter.close();}}

s.close();

gc.collect();

return

unzipfiles;

}public

string getzipfileextention(string

filefullname)

//extension string

string ext =filefullname.substring(index);

if (ext == "

.rar

" || ext == "

.zip")

else}}

上述**便是壓縮檔案的方法,我的測試結果如下:

我示例的**如下:

@陳臥龍的部落格

C 壓縮檔案

首先新增system.io.com pression 注意deflatestream類不能用來壓縮大小超過4gb的檔案。gzipstream同樣不能用來壓縮大小超過4gb的檔案。public void compressfile string srcfile,string dstfile if fil...

C 壓縮檔案

c 壓縮檔案 方法1 filepath想要壓縮檔案的位址 zippath輸出壓縮檔案的位址 private void getfiletozip string filepath,string zippath 方法2 private void filetozip string path,string a...

c 壓縮檔案

引用 using system using system.collections.generic using system.text using microsoft.win32 using system.io using system.diagnostics 獲取winrar.exe路徑 winra...