.NetCore使⽤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, 0, buff.Length);
bw.Close();
fs.Close();
}
getsavefilename/// <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[0];
}
FileInfo fi = new FileInfo(path);
byte[] buff = new byte[fi.Length];
FileStream fs = fi.OpenRead();
fs.Read(buff, 0, 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);
}
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论