【.Net Core】ZipFile类--文件的压缩解压

时间:2022-06-04 20:14:34

【.Net Core】ZipFile类--文件的压缩解压

NuGet引用官网自带的System.IO.Compression.ZipFile;

var filename = "测试压缩解压文件";
var path = Directory.GetCurrentDirectory() + "/wwwroot/file/" + filename + ".pdf";
//这里是获取到文件的byte数组
byte[] fileBuffer1 = Convert.FromBase64String(invData);
//将byte数组转换为文件并保存到指定地址
FileSystem.Bytes2File(fileBuffer1, path);
//添加文件到指定压缩文件中
ZipFile.CreateFromDirectory(Directory.GetCurrentDirectory() + "/wwwroot/file", Directory.GetCurrentDirectory() + "/wwwroot/" + zipFileName);
//删除文件夹下的所有文件
FileSystem.DeleteDirAllFile(Directory.GetCurrentDirectory() + "/wwwroot/file/");
byte[] fileBuffer;
//文件转成byte二进制数组
fileBuffer = FileSystem.File2Bytes(Directory.GetCurrentDirectory() + "/wwwroot/" + zipFileName);
//这里开始上传文件
//将指定 zip 存档中的所有文件都解压缩到文件系统的一个目录下
ZipFile.ExtractToDirectory(Directory.GetCurrentDirectory() + "/wwwroot/" + zipFileName,Directory.GetCurrentDirectory() + "/wwwroot/file");
 public class FileSystem
{
/// <summary>
/// 将byte数组转换为文件并保存到指定地址
/// </summary>
/// <param name="buff">byte数组</param>
/// <param name="savepath">保存地址</param>
public static void Bytes2File(byte[] buff, string savepath)
{
if (System.IO.File.Exists(savepath))
{
System.IO.File.Delete(savepath);
} FileStream fs = new FileStream(savepath, FileMode.CreateNew);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(buff, , buff.Length);
bw.Close();
fs.Close();
} /// <summary>
/// 将文件转换为byte数组
/// </summary>
/// <param name="path">文件地址</param>
/// <returns>转换后的byte数组</returns>
public static byte[] File2Bytes(string path)
{
if (!System.IO.File.Exists(path))
{
return new byte[];
} FileInfo fi = new FileInfo(path);
byte[] buff = new byte[fi.Length]; FileStream fs = fi.OpenRead();
fs.Read(buff, , Convert.ToInt32(fs.Length));
fs.Close(); return buff;
} /// <summary>
/// 删除文件夹下的所有文件
/// </summary>
/// <param name="dirRoot"></param>
public static void DeleteDirAllFile(string dirRoot)
{
DirectoryInfo aDirectoryInfo = new DirectoryInfo(Path.GetDirectoryName(dirRoot));
FileInfo[] files = aDirectoryInfo.GetFiles("*.*", SearchOption.AllDirectories);
foreach (FileInfo f in files)
{
File.Delete(f.FullName);
}
}
}