How i can Extract zip file to flatten files only ? if file exist rename it?

Dani_S 4,501 Reputation points
2023-10-20T09:15:18.71+00:00

Hi,

How i can Extract zip file to flatten files only ? if file exist rename it?

Thanks,

Developer technologies | .NET | .NET MAUI
{count} votes

Accepted answer
  1. Trevor Lacey 85 Reputation points
    2023-10-21T23:19:39.2766667+00:00

    When you use ZipArchive and ZipArchiveEntry, you control the folder destination for each file. For example:

    string zipFilePath = "path/to/your/zipfile.zip";
    string extractionPath = "path/to/extract/folder";
    
    using ZipArchive archive = ZipFile.OpenRead(zipFilePath);
    foreach (ZipArchiveEntry entry in archive.Entries)
    {
        string entryFileName = Path.GetFileName(entry.FullName);
    
        // Handle duplicated file names by adding a unique suffix
        string destFileName = Path.Combine(extractionPath, entryFileName);
        int count = 1;
        while (File.Exists(destFileName))
        {
            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(entryFileName);
            string fileExtension = Path.GetExtension(entryFileName); 
            destFileName = Path.Combine(extractionPath, $"{fileNameWithoutExtension}_{count}{fileExtension}");
            count++;
        }
    
        // Extract the entry while preserving the file name
        entry.ExtractToFile(destFileName, overwrite: true);
    }
    
    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.