简体   繁体   中英

How to zip only file and folder in path in c#

I use this code for zip all file and folder in my path.

using (ZipFile zip = new ZipFile())
{
zip.AddDirectory(@"MyDocuments\ProjectX", "ProjectX");
zip.Save(zipFileToCreate);
}

For example:

  • Folder1
    • Folder2
      • file1
      • file2
      • file3
    • file4
    • file5
    • file6

I zip Folder1, and this code it's working. but this zip all file and folder with Folder1. but i have zip only file and folder in Folder1.

Result my code:

  • MyFileZip

    • Folder1

      • Folder2

        • file1
        • file2
        • file3
      • file4

      • file5
      • file6

But I want this result:

  • MyFileZip

    • Folder2

       - file1 - file2 - file3
    • file4

    • file5
    • file6

I wonder how could you manage to instantiate ZipFile class as its static, any way use this code

    string startPath = @"<path-to-folder1>";
    string zipPath = @"<path-to-output>\MyFileZip.zip";

    ZipFile.CreateFromDirectory(startPath, zipPath);

Just remember that the destination folder can not be same as folder1 or you get an exception claiming process is in use

You could use the following static method override and specify includeBaseDirectory to be false

   public static void CreateFromDirectory (string sourceDirectoryName,
    string destinationArchiveFileName,
    System.IO.Compression.CompressionLevel compressionLevel, bool
    includeBaseDirectory, System.Text.Encoding entryNameEncoding);

Documentation

If the destination Folder of the zipped files should be the same as the source Folder, you could use the User Temp directory as transitory storage.
This because you can't create a Zip file in the same directory that contains the files/folders to compress: it'ld try to zip itself, causing an exception.

string sourceFolder = 
    Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "ProjectX");
string destinationFolder = sourceFolder;
string ZippedFileName = "ZippedFile.zip";

string userTempFolder = Environment.GetEnvironmentVariable("Temp", EnvironmentVariableTarget.User);
string zippedTempFile = Path.Combine(userTempFolder, ZippedFileName);
if (File.Exists(zippedTempFile)) { File.Delete(zippedTempFile); }

ZipFile.CreateFromDirectory(sourceFolder, ZippedFileName);
File.Move(zippedTempFile, Path.Combine(destinationFolder, ZippedFileName));

The last parameter to ZIPFile.CreateFromDirectory, for which you are passing the value true, determines whether the directory itself should be included as the root of the ZIP. If you change this to false it should work as you desire.

ZipFile.CreateFromDirectory(startPath, zipPath,  CompressionLevel.Fastest, false); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM