如何使用 ZipArchive 将.zip保存到文件夹

本文关键字:保存 文件夹 zip 何使用 ZipArchive | 更新日期: 2023-09-27 18:37:08

我做了以下操作,但我在直接中看不到zip文件。C#

  public static void AddToZip(string fileToAdd, string directory)
    {
        string entryName = fileToAdd.Replace(directory, string.Empty);
        string archiveName = entryName.Replace(Path.GetExtension(entryName), ".zip");
        using (ZipArchive za = ZipFile.Open(archiveName, ZipArchiveMode.Create))
        {
            za.CreateEntryFromFile(fileToAdd, entryName, CompressionLevel.Optimal);
        }
    }

这是我关注的链接。http://msdn.microsoft.com/en-us/library/system.io.compression.ziparchive(v=vs.110).aspx

如何使用 ZipArchive 将.zip保存到文件夹

经过一些试验和错误,终于让它工作了。

public static void AddToZip(string fileToAdd, string directory)
    {
        string entryName = fileToAdd.Replace(directory, string.Empty);//name of the file inside zip archive
        string tempDir = Path.Combine(directory, Path.GetFileNameWithoutExtension(entryName));
        if (Directory.Exists(tempDir)) DeleteDirector(tempDir);
        else Directory.CreateDirectory(tempDir);
        System.IO.File.Move(fileToAdd, Path.Combine(tempDir, entryName));//as the CreateFromDirectoy add all the file from the directory provided, we are moving our file to temp dir.
        string archiveName = entryName.Replace(Path.GetExtension(entryName), ".zip"); //name of the zip file.
        ZipFile.CreateFromDirectory(tempDir, Path.Combine(directory, archiveName));
        DeleteDirector(tempDir);
    }
    private static void DeleteDirector(string deletedir)
    {
        foreach (string file in Directory.GetFiles(deletedir))
        {
            System.IO.File.Delete(file);
        }
        Directory.Delete(deletedir);
    }

我知道这不是最好的解决方案。 因此,欢迎您修改/改进它。