900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > c# 把文件压缩成Zip的压缩包格式

c# 把文件压缩成Zip的压缩包格式

时间:2018-09-01 14:49:39

相关推荐

c# 把文件压缩成Zip的压缩包格式

第一个参数:要压缩的文件夹[也可以是文件夹下面的一个文件]

第二个参数:压缩后文件要保存的路径

private static void CreateZipFile(string filesPath, string zipFilePath)

{

if (!Directory.Exists(filesPath))

{

Console.WriteLine("Cannot find directory '{0}'", filesPath);

return;

}

try

{

string[] filenames = Directory.GetFiles(filesPath);

using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFilePath)))

{

s.SetLevel(9); // 压缩级别 0-9

//s.Password = "123"; //Zip压缩文件密码

byte[] buffer = new byte[4096]; //缓冲区大小

foreach (string file in filenames)

{

ZipEntry entry = new ZipEntry(Path.GetFileName(file));

entry.DateTime = DateTime.Now;

s.PutNextEntry(entry);

using (FileStream fs = File.OpenRead(file))

{

int sourceBytes;

do

{

sourceBytes = fs.Read(buffer, 0, buffer.Length);

s.Write(buffer, 0, sourceBytes);

} while (sourceBytes > 0);

}

}

s.Finish();

s.Close();

}

}

catch (Exception ex)

{

Console.WriteLine("Exception during processing {0}", ex);

}

}

----------------------------------------------------------------------------------------------

以上代码直接拉过去用法在下面

string Afterpath = HttpContext.Current.Server.MapPath("~/YaSuo/"); //压缩后要保存的目录【当前程序的目录下面的文件夹】

string Beforepath = HttpContext.Current.Server.MapPath("~/Downloader/");//要压缩的目录【当前程序的目录下面的文件夹】

CreateZip(Beforepath, Afterpath + $"{replace(tablename)}ORM.zip");

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。