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

时间:2015-01-12 13:19:03

标签: c# .net ziparchive

我做了以下操作,但我没有在directroy中看到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

1 个答案:

答案 0 :(得分:0)

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

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);
    }

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

相关问题