复制代码 代码如下:
/// <summary>
/// 压缩文件
/// </summary>
/// <param>源文件路径</param>
/// <param>压缩文件后的保存路径</param>
/// <returns>压缩是否成功</returns>
public bool Compress(string sourceFilePath, string destinationPath)
{
try
{
string[] filenames = Directory.GetFiles(sourceFilePath);
using (ZipOutputStream zs = new ZipOutputStream(File.Create(destinationPath)))
{
zs.SetLevel(9);
byte[] buffer = new byte[4096];
foreach (string file in filenames)
{
ZipEntry entry = new ZipEntry(Path.GetFileName(file));
entry.DateTime = DateTime.Now;
zs.PutNextEntry(entry);
using (FileStream fs = File.OpenRead(file))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0, buffer.Length);
zs.Write(buffer, 0, sourceBytes);
}
while (sourceBytes > 0);
}
}
zs.Finish();
zs.Flush();
zs.Close();
}
}
catch (Exception)
{
return false;
}
return true;
} public bool DeCompress(string sourceFilePath, string destinationPath)
{
try
{
using (ZipInputStream zs = new ZipInputStream(File.OpenRead(sourceFilePath)))
{
ZipEntry entry = null;
//解压缩*.rar文件运行至此处出错:Wrong Local header signature: 0x21726152,解压*.zip文件不出错
while ((entry = zs.GetNextEntry()) != null)
{
string directoryName = Path.GetDirectoryName(entry.Name);
string fileName = Path.GetFileName(entry.Name);
if (!string.IsNullOrEmpty(fileName))
{
using (FileStream streamWriter = File.Create(destinationPath + entry.Name))
{
int size = 2048;
byte[] data = new byte[size];
while (true)
{
size = zs.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else
{
break;
}
}
}
}
}
}
}
catch (System.Exception)
{
return false;
}
return true;
}
复制代码 代码如下:
public bool DeCompressRAR(string sourceFilePath, string destinationPath)
{
try
{
string SeverDir = @"D:/Program Files/WinRAR";//rar.exe的要目录
Process ProcessDecompression = new Process();
ProcessDecompression.StartInfo.FileName = SeverDir + "//rar.exe";
Directory.CreateDirectory(sourceFilePath);
ProcessDecompression.StartInfo.Arguments = " X " + sourceFilePath + " " + destinationPath;
ProcessDecompression.Start();
while (!ProcessDecompression.HasExited)
{
//nothing to do here.
}
return true;
}
catch (System.Exception)
{
return false;
}
}
新闻热点
疑难解答
图片精选