Sample C# .net code for zipping a file using 7zip

后端 未结 5 1606
终归单人心
终归单人心 2020-12-19 09:30

I have installed 7-zip 4.65 on my machine at C:\\Program files. I want to use it in C# code to zip a file. The file name will be provided by the user dynamically. Can any on

5条回答
  •  失恋的感觉
    2020-12-19 09:50

    lots of answer given above but i used this below mention code to zip or unzip a file using 7zip

    you must have 7zip application in your system .

         public void ExtractFile(string source, string destination)
            {
                // If the directory doesn't exist, create it.
                if (!Directory.Exists(destination))
                    Directory.CreateDirectory(destination);
    
                string zPath = @"C:\Program Files\7-Zip\7zG.exe";
    // change the path and give yours 
                try
                {
                    ProcessStartInfo pro = new ProcessStartInfo();
                    pro.WindowStyle = ProcessWindowStyle.Hidden;
                    pro.FileName = zPath;
                    pro.Arguments = "x \"" + source + "\" -o" + destination;
                    Process x = Process.Start(pro);
                    x.WaitForExit();
                }
                catch (System.Exception Ex) {
                  //DO logic here 
                  }
            }
    

    to create zip file

    public void CreateZip()
    {
        string sourceName = @"d:\a\example.txt";
        string targetName = @"d:\a\123.zip";
        ProcessStartInfo p = new ProcessStartInfo();
        p.FileName = @"C:\Program Files\7-Zip\7zG.exe";
        p.Arguments = "a -tgzip \"" + targetName + "\" \"" + sourceName + "\" -mx=9";
        p.WindowStyle = ProcessWindowStyle.Hidden;
        Process x = Process.Start(p);
        x.WaitForExit();
    }
    

提交回复
热议问题