gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:05:34 25 4
gpt4 key购买 nike

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();

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

最佳答案

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

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();

关于c# - 从 Process.StandardOutput 重定向二进制数据会导致数据损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8988226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com