doNet Core中解压zip

2023-12-19 21:36:10

doNet Core4.0解压zip文件

1、ZipInputStream.cs
public class ZipHelper
{
///
/// 解压缩一个 zip 文件。
///
/// The ziped file.
/// The STR directory.
/// 是否覆盖已存在的文件。
public static void UnZip(string zipedFile, string strDirectory, bool overWrite)
{
if (strDirectory == “”)
strDirectory = Directory.GetCurrentDirectory();
if (!strDirectory.EndsWith(“\”))
strDirectory = strDirectory + “\”;
using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipedFile)))
{
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = “”;
string pathToZip = “”;
pathToZip = theEntry.Name;
if (pathToZip != “”)
directoryName = Path.GetDirectoryName(pathToZip) + “\”;
string fileName = Path.GetFileName(pathToZip);
Directory.CreateDirectory(strDirectory + directoryName);

if (fileName != “”)
{
if ((File.Exists(strDirectory + directoryName + fileName) && overWrite) || (!File.Exists(strDirectory + directoryName + fileName)))
{
using (FileStream streamWriter = File.Create(strDirectory + directoryName + fileName))
{
int size = 2048;
byte[] data = new byte[2048];
while (true)
{
size = s.Read(data, 0, data.Length);
if (size > 0)
streamWriter.Write(data, 0, size);
else
break;
}
streamWriter.Close();
}
}
}
}
s.Close();
}
}

}
2、在页面里上传压缩包后解压后读取
private string zipDir;
private string excelFile = “”;

    public void ReadZip(string zipFile)
    {
        string zipFileName = Path.GetFileNameWithoutExtension(zipFile);
        zipDir = Path.GetDirectoryName(zipFile);
        ZipHelper.UnZip(zipFile, Path.GetDirectoryName(zipFile),  true);

        if (string.IsNullOrEmpty(zipDir))
            return;
        string[] files = Directory.GetFiles(zipDir);
        foreach (string file in files)
        {
            string fileName = Path.GetFileNameWithoutExtension(file);
            if (string.Compare(fileName, "DATAORDER_DATA", true) == 0)
            {
                excelFile = file;
            }
        }
    }

文章来源:https://blog.csdn.net/qq_41760419/article/details/135086675
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。