缺少EOF时如何从C#程序的Process中将多个gz文件合并为一个

时间:2019-06-18 20:21:19

标签: c# linux

我在一个目录中有多个.gz文件(2个或更多),至少有一个文件缺少文件标记的末尾。我们的C#进程无法读取缺少文件结尾的文件,但是由于它们来自第三方,因此我们无法控制它们的创建方式。

因此,我们一直在手动运行以下Linux命令:

cat file1.gz file2.gz > newFile.gz

为了使其自动化,我正在寻找一种方法来利用C#中的Process功能来触发相同的命令,但这仅在Cygwin或其他Linux shell中可用。在我的示例中,我使用的是git bash,但它可能是Powershell或Cygwin或运行在Windows机器上的任何其他可用的Linux shell。

以下代码不会失败,但是不会按预期运行。我想知道是否有人对如何做到这一点有任何建议,或者对其他方法有任何建议吗?

假定已成功设置和初始化工作目录,因此文件位于运行进程的位置。

Process bashProcess = new Process();
bashProcess.StartInfo.FileName = @"..\Programs\Git\git-bash.exe";
bashProcess.StartInfo.UseShellExecute = false;
bashProcess.StartInfo.RedirectStandardInput = true;
bashProcess.StartInfo.RedirectStandardOutput = true;

bashProcess.Start();

bashProcess.StandardInput.WriteLine("cat file1.gz file2.gz > newFile.gz");
bashProcess.StandardInput.WriteLine("exit");
bashProcess.StandardInput.Flush();
.
.
.
bashProcess.WaitForExit();

我希望newFile.gz已创建

1 个答案:

答案 0 :(得分:0)

我能够使用DOS命令找到问题的解决方案,并从CSharp生成cmd进程。

我的代码现在看起来像这样,避免了必须从Windows启动基于Linux的外壳,并且Windows中的copy命令与cat具有相同的作用:

Process proc = new Process();
proc.EnableRaisingEvents = false;
proc.StartInfo.FileName = "cmd";
proc.StartInfo.Arguments = @"/C pushd \\server\folder && copy *.txt.gz /b 
    combined.gz";
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.UseShellExecute = false;
proc.Start();
proc.WaitForExit();

System.Threading.Thread.Sleep(2000);
string line = proc.StandardOutput.ReadLine();

while (line != null)
{
    output.Append(line);
    line = proc.StandardOutput.ReadLine();
}