Search code examples
c#zipfile-copying

Changing extension, extract, delete zip, merge new folder


I have a unique file extension which is really just a zip. I am trying to in one event change the extension name, extract the files, then merge them all into one file.

I can move the file, change the extension but it stops there. It won't extract the files. I have tried to put a Thread.Sleep(10000) in thinking maybe it didn't see the zips because they were still copying but that didn't work either.

string path = txtField.text;
string[] originalFiles = Directory.GetFiles(path, "*.unique");
string[] newZips = Directory.GetFiles(path, "*.zip");
try
{
    foreach (var item in originalFiles)
    {
        File.Copy(item, Path.ChangeExtension(item, ".zip"));
    }
    foreach (var item in newZips)
    {
        ZipFile.CreateFromDirectory(path, item);
        Zipfile.ExtractToDirectory(item, path);
    }
}
catch (exception ex)
{
    MessageBox.Show(ex.Message, "Fail....");
}

Solution

  • The problem is that newZips gets set before you actually create the renamed zip files. You would need to move the line:

    string[] newZips = Directory.GetFiles(path, "*.zip");
    

    ..so that it appears after the first foreach loop.

    If your ultimate objective is only to create a new zip with the contents of the *.unique files, perhaps you can avoid renaming the files. You could do something similar to the following to extract the files to a temporary folder and create the new zip from those files:

    string path = txtField.text;
    string[] originalFiles = Directory.GetFiles(path, "*.unique");
    
    try
    {
        var extractedFilesPath = Path.Combine(path, "ExtractedFiles");
        var newZipFile = Path.Combine(path, "NewZipFile.zip");
    
        foreach (var item in originalFiles)
        {
            ZipFile.ExtractToDirectory(item, extractedFilesPath);
        }
    
        ZipFile.CreateFromDirectory(extractedFilesPath, newZipFile);
    
        Directory.Delete(extractedFilesPath, true);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Fail....");
    }