C# zip、excel文件的解压和压缩

安装SharpCompress
代码如下

/// 
/// 解压zip到指定文件夹
/// 
/// zip压缩文件xlsx文件也可以
/// 解压的文件夹
public void DecompressionZip(string zipFile, string targetPath)
{
    if (Directory.Exists(targetPath))
    {
        Directory.Delete(targetPath, true);
    }
    Directory.CreateDirectory(targetPath);
    var archive = ArchiveFactory.Open(zipFile);
    foreach (var entry in archive.Entries)
    {
        if (!entry.IsDirectory)
        {
            Console.WriteLine(entry.Key);
            entry.WriteToDirectory(targetPath, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true });
        }
    }
    archive.Dispose();
}

/// 
/// 把文件夹压缩为zip
/// 
/// 文件夹路径
/// 压缩后的文件名字不一定非得是zip后缀,比如xlsx后缀
public void CompressFolderToZip(string folderPath, string zipPath)
{
    // 中文乱码
    SharpCompress.Common.ArchiveEncoding ArchiveEncoding = new SharpCompress.Common.ArchiveEncoding();
    ArchiveEncoding.Default = Encoding.GetEncoding("utf-8");
    SharpCompress.Writers.WriterOptions options = new SharpCompress.Writers.WriterOptions(CompressionType.Deflate);
    options.ArchiveEncoding = ArchiveEncoding;

    using (var archive = ZipArchive.Create())
    {
        archive.AddAllFromDirectory(folderPath);
        using (var zip = System.IO.File.OpenWrite(zipPath))
            archive.SaveTo(zip, options);
    }
}

你可能感兴趣的:(dotnet,c#,前端,javascript)