How to Unzip all .Zip file from Folder using C# 4.0 and without using any OpenSource Dll?

前端 未结 6 1446
礼貌的吻别
礼貌的吻别 2020-12-09 03:02

I have a folder containing .ZIP files. Now, I want to Extract the ZIP Files to specific folders using C#, but without using any external assembly or the .Ne

6条回答
  •  庸人自扰
    2020-12-09 03:46

    I had the same question and found a great and very simple article that solves the problem. http://www.fluxbytes.com/csharp/unzipping-files-using-shell32-in-c/

    you'll need to reference the COM library called Microsoft Shell Controls And Automation (Interop.Shell32.dll)

    The code (taken untouched from the article just so you see how simple it is):

    public static void UnZip(string zipFile, string folderPath)
    {
        if (!File.Exists(zipFile))
            throw new FileNotFoundException();
    
        if (!Directory.Exists(folderPath))
            Directory.CreateDirectory(folderPath);
    
        Shell32.Shell objShell = new Shell32.Shell();
        Shell32.Folder destinationFolder = objShell.NameSpace(folderPath);
        Shell32.Folder sourceFile = objShell.NameSpace(zipFile);
    
        foreach (var file in sourceFile.Items())
        {
            destinationFolder.CopyHere(file, 4 | 16);
        }
    }
    

    highly recommend reading the article- he brings an explenation for the flags 4|16

    EDIT: after several years that my app, which uses this, has been running, I got complaints from two users that all of the sudden the app stopped working. it appears that the CopyHere function creates temp files/folders and these were never deleted which caused problems. The location of these files can be found in System.IO.Path.GetTempPath().

提交回复
热议问题