如何使用cmd将C#应用程序的输出管道传输到文本?

时间:2015-01-08 13:39:14

标签: c# cmd

我正在运行一个在后台使用控制台应用的应用

当我在cmd read-info.exe Myfile.file >fileinfo.txt中执行此操作时,它将在路径文件夹中创建文件fileinfo.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;
}

3 个答案:

答案 0 :(得分:2)

看到这一点 - 我认为这是必要的:{{3p>

从上面的链接复制:

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

答案 1 :(得分:0)

使用cmd /C运行控制台命令。

string command = "cmd /C read-info.exe " + textBox1.Text +"> File.txt";

答案 2 :(得分:0)

得到它的工作感谢@crashmstr

它输出文件为out.txt所以只需要注释掉File.Delete(“out.txt”);