如何使用命令提示符使用c#并逐行获取结果
本文关键字:逐行 获取 结果 何使用 命令提示符 | 更新日期: 2023-09-27 18:28:49
我有一个程序,其中有一个.exe文件。.exe的工作是扫描目录中是否有损坏的文件。如果通过以下格式的命令提示符访问,我会得到扫描的结果
"exe的位置"要扫描的文件或文件夹"
我得到的结果是随着扫描的进行。就像一样
D:'A scanned
D:'B scanned
D:'C scanned
D:'D scanned
现在我的问题是如何使用c#逐行获得结果。
我使用下面的一组代码,我只得到最终结果。我需要逐行的输出
代码如下:
string tempGETCMD = null;
Process CMDprocess = new Process();
System.Diagnostics.ProcessStartInfo StartInfo = new System.Diagnostics.ProcessStartInfo();
StartInfo.FileName = "cmd"; //starts cmd window
StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
StartInfo.CreateNoWindow = true;
StartInfo.RedirectStandardInput = true;
StartInfo.RedirectStandardOutput = true;
StartInfo.UseShellExecute = false; //required to redirect
CMDprocess.StartInfo = StartInfo;
CMDprocess.Start();
System.IO.StreamReader SR = CMDprocess.StandardOutput;
System.IO.StreamWriter SW = CMDprocess.StandardInput;
SW.WriteLine("@echo on");
SW.WriteLine(@"E:'Scanner'Scanner.exe -r E:'Files to be scanned'"); //the command you wish to run.....
SW.WriteLine("exit"); //exits command prompt window
tempGETCMD = SR.ReadToEnd(); //returns results of the command window
SW.Close();
SR.Close();
return tempGETCMD;
这方面的任何帮助都将被认可
谢谢,
我认为您必须使用一个专用线程来读取StandardOutput
流中的每一行新行,如下所示:
//This will append each new line to your textBox1 (multiline)
private void AppendLine(string line)
{
if (textBox1.InvokeRequired){
if(textBox1.IsHandleCreated) textBox1.Invoke(new Action<string>(AppendLine), line);
}
else if(!textBox1.IsDisposed) textBox1.AppendText(line + "'r'n");
}
//place this code in your form constructor
Shown += (s, e) => {
new Thread((() =>
{
while (true){
string line = CMDProcess.StandardOutput.ReadLine();
AppendLine(line);
//System.Threading.Thread.Sleep(100); <--- try this to see it in action
}
})).Start();
};
//Now every time your CMD outputs something, the lines will be printed (in your textBox1) like as you see in the CMD console window.