您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關怎么在C#項目中利用7z實現一個文件壓縮功能,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
1.關于7z
7z是一種主流的 壓縮格式,它擁有極高的壓縮比。在計算機科學中,7z是一種可以使用多種壓縮算法進行數據壓縮的檔案格式。主要有以下特點:
2.解壓縮實現代碼
實現對文件的解壓縮方法是通過cmd命令,調用7z程式通過cmd命令實現對文件進行解壓和壓縮的操作,具體實現代碼如下:
壓縮的cmd命令:"7Z a -tzip " + zipPath + " " + filePath;
public ExecutionResult CompressFile(string filePath, string zipPath)//運行DOS命令 { ExecutionResult exeRes = new ExecutionResult(); exeRes.Status = true; try { Process process = new Process(); process.StartInfo.FileName = "cmd.exe"; string message = ""; string command1 = "c:"; string command2 = @"cd\"; string command3 = @"cd C:\Progra~1\7-Zip"; string command4 = ""; command4 = "7Z a -tzip " + zipPath + " " + filePath; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.CreateNoWindow = true; process.Start(); process.StandardInput.WriteLine(command1); process.StandardInput.WriteLine(command2); process.StandardInput.WriteLine(command3); process.StandardInput.WriteLine(command4); process.StandardInput.WriteLine("exit"); message = process.StandardOutput.ReadToEnd(); //要等壓縮完成后才可以來抓取這個壓縮文件 process.Close(); if (!message.Contains("Everything is Ok")) { exeRes.Status = false; exeRes.Message = message; } else { exeRes.Anything = zipPath; } } catch (Exception ex) { exeRes.Message = ex.Message; } return exeRes; }
解壓的cmd命令:"7Z x -tzip " + zipPath + " -o" + filePath + " -y";
public ExecutionResult DeCompressFile( string zipPath, string filePath)//運行DOS命令 { ExecutionResult exeRes = new ExecutionResult(); exeRes.Status = true; try { Process process = new Process(); process.StartInfo.FileName = "cmd.exe"; string message = ""; string command1 = "c:"; string command2 = @"cd\"; string command3 = @"cd C:\Progra~1\7-Zip"; string command4 = ""; command4 = "7Z x -tzip " + zipPath + " -o" + filePath + " -y"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.CreateNoWindow = true; process.Start(); process.StandardInput.WriteLine(command1); process.StandardInput.WriteLine(command2); process.StandardInput.WriteLine(command3); process.StandardInput.WriteLine(command4); process.StandardInput.WriteLine("exit"); //process.WaitForExit(); message = process.StandardOutput.ReadToEnd();//要等壓縮完成后才可以來抓取這個壓縮文件 process.Close(); if (!message.Contains("Everything is Ok")) { exeRes.Status = false; exeRes.Message = message; } else { exeRes.Anything = filePath; } } catch (Exception ex) { exeRes.Message = ex.Message; } return exeRes; }
看完上述內容,你們對怎么在C#項目中利用7z實現一個文件壓縮功能有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。