从Process.StandardOutput重定向二进制数据会导致数据损坏

时间:2012-01-24 14:10:32

标签: c# encoding command-line process

除了this问题,我还有另一个问题。我尝试从外部进程获取二进制数据,但数据(图像)似乎已损坏。下面的屏幕截图显示了损坏:左图像是通过在命令行执行程序完成的,右边是代码。 enter image description here

我的代码到目前为止:

var process = new Process
{
  StartInfo =
  {
    Arguments = string.Format(@"-display"),
    FileName = configuration.PathToExternalSift,
    RedirectStandardError = true,
    RedirectStandardInput = true,
    RedirectStandardOutput = true,
    UseShellExecute = false,
    CreateNoWindow = true,
  },
  EnableRaisingEvents = true
};

process.ErrorDataReceived += (ProcessErrorDataReceived);

process.Start();
process.BeginErrorReadLine();

//Reads in pbm file.
using (var streamReader = new StreamReader(configuration.Source))
{
  process.StandardInput.Write(streamReader.ReadToEnd());
  process.StandardInput.Flush();
  process.StandardInput.Close();
}
//redirect output to file.
using (var fileStream = new FileStream(configuration.Destination, FileMode.OpenOrCreate))
{
  process.StandardOutput.BaseStream.CopyTo(fileStream);
}

process.WaitForExit();

这是某种编码问题吗?我使用了提到here的Stream.CopyTo-Approach来避免出现问题。

1 个答案:

答案 0 :(得分:5)

我发现了问题。输出的重定向是正确的,输入的读取似乎是问题。所以我改变了代码:

using (var streamReader = new StreamReader(configuration.Source))
{
  process.StandardInput.Write(streamReader.ReadToEnd());
  process.StandardInput.Flush();
  process.StandardInput.Close();
}

using (var fileStream = new StreamReader(configuration.Source))
{
  fileStream.BaseStream.CopyTo(process.StandardInput.BaseStream);
  process.StandardInput.Close();
}

不行吗!

对于可能遇到同样问题的所有人,这里是更正后的代码:

var process = new Process
{
  StartInfo =
  {
    Arguments = string.Format(@"-display"),
    FileName = configuration.PathToExternalSift,
    RedirectStandardError = true,
    RedirectStandardInput = true,
    RedirectStandardOutput = true,
    UseShellExecute = false,
    CreateNoWindow = true,
  },
  EnableRaisingEvents = true
};

process.ErrorDataReceived += (ProcessErrorDataReceived);

process.Start();
process.BeginErrorReadLine();

//read in the file.
using (var fileStream = new StreamReader(configuration.Source))
{
    fileStream.BaseStream.CopyTo(process.StandardInput.BaseStream);
    process.StandardInput.Close();
}
//redirect output to file.
using (var fileStream = new FileStream(configuration.Destination, FileMode.OpenOrCreate))
{
    process.StandardOutput.BaseStream.CopyTo(fileStream);
}

process.WaitForExit();