Skip to main content
 首页 » 编程设计

c#之如何使用 C# Stream Reader 保存进程的完成

2024年02月24日16webabcd

我有一个程序,它使用 CMD 程序来执行各种争论。

在普通 CMD 中有效的参数是 C:\temp\bin\fls.exe -m C: -r C:\temp\image.dd > C:\temp\bin\ntfs.bodyfile 。

我编写的 C# 程序只能运行到 C:\temp\bin\fls.exe -m C: -r C:\temp\image.dd 但不会执行 > C:\temp\bin\ntfs.bodyfile 表示将进程保存到ntfs.bodyfile中。

我已经阅读了许多其他网站,它们都指出我的程序缺少流读取器的问题,无法将完成的过程保存到文件中。那么有人可以建议我的程序以允许将过程保存到文件中吗?谢谢!

一个具有相同问题的类似网站是:StreamReader to file?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using Microsoft.Win32; 
using System.Diagnostics; 
 
namespace ConsoleApplication1 
{ 
class Program 
{ 
   static void Main(string[] args) 
   { 
       Process process = new Process(); 
       process.StartInfo.FileName = "C:\\temp\\bin\\fls.exe"; 
       process.StartInfo.Arguments = "-m C: -r C:\\temp\\image.dd >  
       C:\\temp\\bin\\ntfs.bodyfile"; 
       process.StartInfo.UseShellExecute = false; 
       process.StartInfo.RedirectStandardOutput = true; 
       process.StartInfo.RedirectStandardInput = true; 
       process.StartInfo.RedirectStandardError = true; 
       process.Start(); 
 
       System.IO.StreamReader reader = process.StandardOutput; 
       string sRes = reader.ReadToEnd(); 
       Console.WriteLine(sRes); 
       reader.Close();   
   }    
 } 
} 

请您参考如下方法:

它是执行重定向的 shell,因此您的参数列表的一部分被直接传递给 fls。你应该删除它。

您可以直接从标准输出和错误中读取数据,并以此方式保存数据 - 或者您可以调用 cmd 并为其提供所有参数以使其重定向输出。

请注意,如果您确实使用标准输出和标准错误,您可能应该从不同的线程读取其中之一——或者不要重定向它。目前,如果进程将大量数据写入标准错误,您将无法读取它,它最终会耗尽缓冲区空间并阻塞。