【小5聊】C#使用ZipFile压缩类来实现文件压缩和解压

【效果】

【压缩】 

先创建压缩文件然后分别将各个文件添加到压缩文件里

public string FileToZip()
{
    string path1= "/wwwroot/filetozip/" + Guid.NewGuid().ToString()+ ".zip";
    string path2= Directory.GetCurrentDirectory() + path1;

    try
    {

        string oneFile = Directory.GetCurrentDirectory() + "/wwwroot/images/1.jpg";
        string twoFile = Directory.GetCurrentDirectory() + "/wwwroot/images/2.jpg";

        using (ZipArchive zip= ZipFile.Open(path2, ZipArchiveMode.Create))
        {
            zip.CreateEntryFromFile(oneFile, System.IO.Path.GetFileName(oneFile));
            zip.CreateEntryFromFile(twoFile, System.IO.Path.GetFileName(twoFile));
        }
    }
    catch (Exception ex)
    {

    }

    return path1;
}

【解压】

public string ZipToFile(string zipFileName)
{
    string zippath= Directory.GetCurrentDirectory() + zipFileName;
    string filepath= Directory.GetCurrentDirectory() + "/wwwroot/ziptofile/";

    try
    {
        ZipFile.ExtractToDirectory(zippath, filepath);
    }
    catch (Exception ex)
    {

    }

    return "";
}

猜你喜欢

转载自blog.csdn.net/lmy_520/article/details/109582155