How To Programmatically Unzip A .Zip File

Hello everyone,

Since writing my last post on the log parser, I’ve added some new functionality and refactored the project. One of those features is a method for unzipping files in the .zip format, as this was something that was taking a long time to do manually for hundreds of files. I found this post on using Windows Shell, which fit my needs just fine for a small amount of written lines. However, if anyone has any suggestions on why this wouldn’t be good or know of a way that would be more elegant, please feel free to leave a comment. The efficiency seems to be just fine for my needs, but wouldn’t mind tips for security or more efficiency.

public static void Unzip(string inputFile)
    dynamic shellApplication = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"));
    dynamic compressedFolderContents = shellApplication.NameSpace(inputFile).Items;
    dynamic destinationFolder = shellApplication.NameSpace(Path.GetDirectoryName(inputFile));

I implemented multi-select as well, so I have to loop through these selected files in order to unzip them. Also, just for cleanliness, I delete the original zip file after unzipping completes.

using (var oFile = new OpenFileDialog())
    oFile.Filter = "Log Files (*.log*)|*.log*";
    oFile.Multiselect = true;
    var result = oFile.ShowDialog();
    if (result == DialogResult.OK)
        inputFile = oFile.FileNames;
        totalNumberOfFiles = inputFile.Count();
        for (int i = 0; i < inputFile.Count(); i++)
            if (inputFile[i].Contains(".zip"))
                string path = Path.GetDirectoryName(inputFile[i]);
                File.Delete(inputFile[i]); // DELETES ZIP FILE
                inputFile[i] = path + "\\" + Path.GetFileNameWithoutExtension(inputFile[i]); // SETS THE INPUT FILE TO THE UNZIPPED FILE
        return inputFile;
        Console.WriteLine("A file was not selected. Press any key to close...");
        return null;

…and that’s all for today. Leave a comment if you have any questions or suggestions on how to make this code better.

Thanks for reading!


2 thoughts on “How To Programmatically Unzip A .Zip File

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s