如何使用 cmd 将 C# 应用程序的输出管道传输到文本
本文关键字:管道 输出 传输 文本 应用程序 何使用 cmd | 更新日期: 2023-09-27 18:36:49
我正在运行一个在后台使用控制台应用程序的应用程序
当我在cmd read-info.exe Myfile.file >fileinfo.txt
中执行此操作时,它将在路由文件夹中创建文件文件信息.txt。
但是当我在代码中执行此操作时,没有任何反应,为什么?
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog theDialog = new FolderBrowserDialog();
theDialog.RootFolder = System.Environment.SpecialFolder.MyComputer;
if (theDialog.ShowDialog() == DialogResult.OK)
{
textBox1.Text = theDialog.SelectedPath.ToString();
string command = "read-info.exe " + textBox1.Text +"> File.txt";
string retur = CMD(command);
}
}
static string CMD(string args)
{
string cmdbat = "cd " + Application.StartupPath.Replace("''", "/") + "'r'n";
cmdbat += args + " >> out.txt'r'n";
cmdbat += "exit'r'n";
File.WriteAllText("cmd.bat", cmdbat);
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.Arguments = "";
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = Application.StartupPath;
startInfo.CreateNoWindow = true;
startInfo.FileName = Application.StartupPath + "''cmd.bat";
process.StartInfo = startInfo;
process.Start();
process.WaitForExit();
System.Threading.Thread.Sleep(5000);
string cmdOut = File.ReadAllText("out.txt");
File.Delete("cmd.bat");
File.Delete("out.txt");
return cmdOut;
}
看到这个 - 我叮叮当当这是必要的:http://www.dotnetperls.com/redirectstandardoutput
从上面的链接复制:
using System;
using System.Diagnostics;
using System.IO;
class Program
{
static void Main()
{
//
// Setup the process with the ProcessStartInfo class.
//
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = @"C:'7za.exe"; // Specify exe name.
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
//
// Start the process.
//
using (Process process = Process.Start(start))
{
//
// Read in all the text from the process with the StreamReader.
//
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
Console.Write(result);
}
}
}
}
使用 cmd/C 来运行控制台命令。
string command = "cmd /C read-info.exe " + textBox1.Text +"> File.txt";
多
亏了@crashmstr
它输出文件作为输出.txt所以只需要注释掉File.Delete("out.txt");