1. 程式人生 > 實用技巧 >C#呼叫Linux系統命令執行檔案合併操作

C#呼叫Linux系統命令執行檔案合併操作

專案用docker部署在了Linux伺服器中,大附件分片上傳後需要進行檔案合併,為提高合併速度,使用系統命令進行操作,程式碼如下:

      #region 執行Linux系統命令
                try
                {
                    //拼接合並命令中的檔案字串,sourcePath為檔案塊所在目錄,targetPath為合併檔案的目錄
                    var fileStr = "";
                    for (var i = 0; i < files.Length; i++)
                    {
                        fileStr 
+= fileStr.Length > 0 ? " " + sourcePath + i.ToString() : sourcePath + i.ToString(); } //合併檔案命令(cat /home/test/1.txt home/test/2.txt >home/test/all.txt) string command = "cat " + fileStr + " >" + targetPath.Replace("\\", "/");
//執行結果 string result = ""; using (System.Diagnostics.Process proc = new System.Diagnostics.Process()) { proc.StartInfo.FileName = "/bin/bash"; proc.StartInfo.Arguments = "-c \" " + command + " \""
; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.Start(); result += proc.StandardOutput.ReadToEnd(); result += proc.StandardError.ReadToEnd(); proc.WaitForExit(); } } catch (Exception ex) { logger.Error("合併報錯:" + ex.Message); } #endregion