【【【【C#壓縮檔案】】】】
方法1:
//【filepath想要壓縮檔案的位址】
//【zippath輸出壓縮檔案的位址】
private void GetFileToZip(string filepath,string zippath)
{
FileStream fs = File.OpenRead(filepath);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
FileStream ZipFile = File.Create(zippath);
ZipOutputStream ZipStream = new ZipOutputStream(ZipFile);
ZipEntry ZipEntry = new ZipEntry(輸出的檔案名稱);
ZipStream.PutNextEntry(ZipEntry);
ZipStream.SetLevel(6);
ZipStream.Write(buffer, 0, buffer.Length);
ZipStream.Finish();
ZipStream.Close();
}
方法2:
private void FileToZip(string path,string address)
{
string name = openFileDialog1.FileName.Substring(openFileDialog1.FileName.LastIndexOf("\\")+1);
FileStream StreamToZip = new FileStream(path, FileMode.Open, FileAccess.Read);
FileStream ZipFile = File.Create(address);
ZipOutputStream ZipStream = new ZipOutputStream(ZipFile);
//壓縮檔案
ZipEntry ZipEntry = new ZipEntry(name);
ZipStream.PutNextEntry(ZipEntry);
ZipStream.SetLevel(6);
byte[] buffer = new byte[StreamToZip.Length];
StreamToZip.Read(buffer, 0, Convert.ToInt32(StreamToZip.Length));
ZipStream.Write(buffer, 0, Convert.ToInt32(StreamToZip.Length));
ZipStream.Finish();
ZipStream.Close();
StreamToZip.Close();
}
【【【【【【C#解壓檔案】】】】】】
private void ZipToFile(string path, string addres)
{
ZipInputStream s = new ZipInputStream(File.OpenRead(path));
ZipEntry fileEntry;
while ((fileEntry = s.GetNextEntry()) != null)
{
string filename = Path.GetFileName(fileEntry.Name);
if (filename != "")
{
filename = addres + "\\" + filename;
FileStream streamWriter = File.Create(filename);
int size = 2048;
byte[] buffer = new byte[s.length];
size = s.Read(buffer, 0, size);
streamWriter.Write(buffer, 0, size);
streamWriter.Close();
}
}
s.Close();
}
【【【【【【C#壓縮目錄】】】】】】
方法1:
//【arg[0]要壓縮的目錄】
//【arg[1]輸出的壓縮檔案】
private void DirectoryToZip(string path, string address)
{
//擷取目前檔案夾中所有的檔案
string[] filenames = Directory.GetFiles(path);
Crc32 crc = new Crc32();
//建立輸出檔案(ZIP格式的檔案)
ZipOutputStream zos = new ZipOutputStream(File.Create(address));
zos.SetLevel(6);
//周遊所有的檔案
foreach (string name in filenames)
{
FileStream fs = File.OpenRead(name);
byte[] buffer = new byte[fs.Length];
//讀取檔案
fs.Read(buffer, 0, Convert.ToInt32(fs.Length));
//擷取檔案的檔案名稱和字尾名
string file = Path.GetFileName(name);
//輸出檔案的名稱
ZipEntry entry = new ZipEntry(file);
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
zos.PutNextEntry(entry);
zos.Write(buffer, 0, Convert.ToInt32(fs.Length));
fs.Close();
}
zos.Finish();
zos.Close();
}
【【【【【【【【C#讀取壓縮檔案(将壓縮檔案轉換為二進制)】】】】】】】】
private void GetZipToByte(){
string path = @"C:\Documents and Settings\Administrator\桌面\檔案.rar";
FileStream fs = new FileStream(path, FileMode.Open);
bytes = new byte[fs.Length];
int count = Convert.ToInt32(fs.Length);
fs.Read(bytes, 0, count);
}
【【【【【【【【C#将二進制轉換為壓縮檔案】】】】】】】】
private void GetByteToZip()
{
string path = @"F:\dom.rar";//壓縮檔案的位址
File.WriteAllBytes(path, bytes);
}