如何从代码运行命令行命令

时间:2009-05-28 08:35:20

标签: c# .net command-line batch-file

我需要做两件事:运行批处理文件(工作正常),然后运行命令(不起作用)。 该命令的方法抛出异常'file not found'。如果我打开一个cmd窗口,并输入命令,它就可以正常工作。

  private static void Rescan()
    {
        //System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("DEVCON ReScan");
        //psi.RedirectStandardOutput = true;
        //psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
        //psi.UseShellExecute = false;
        //System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi);
        System.Diagnostics.Process proc = new System.Diagnostics.Process();
        proc.StartInfo.FileName = "DEVCON ReScan";
        proc.StartInfo.RedirectStandardError = true;
        proc.StartInfo.RedirectStandardOutput = true;
        proc.StartInfo.UseShellExecute = false;
        proc.Start();
        proc.WaitForExit();
        System.IO.StreamReader myOutput = proc.StandardOutput;
        proc.WaitForExit(4000);
        if (proc.HasExited)
        {
            string output = myOutput.ReadToEnd();
            FileIO.WriteLog(_writePath, output);
        }

    }

注释代码也会引发相同的异常。

3 个答案:

答案 0 :(得分:9)

DEVCON ReScan真的是可执行文件的名称吗?我猜可执行文件是DEVCON,而ReScan是一个参数。这意味着您必须将StartInfo.FileName设置为“DEVCON”并将StartInfo.Arguments设置为“ReScan”。

答案 1 :(得分:0)

DEVCON应用程序实际上是否在工作目录中? 否则,除非您指定它的完整路径,否则它将无法工作。

此外你必须指定扩展名,所以我想你会选择“Devcon.exe”, 并指定不在文件名中但在参数中的参数:)

答案 2 :(得分:0)

试试这个:

        ProcessStartInfo psi = new ProcessStartInfo();            
        psi.FileName = Environment.GetEnvironmentVariable("comspec");
        psi.CreateNoWindow = true;
        psi.RedirectStandardError = true;
        psi.RedirectStandardInput = true;
        psi.RedirectStandardOutput = true;
        psi.UseShellExecute = false;

        Process p = Process.Start(psi);

        ConsoleColor fc = Console.ForegroundColor;

        StreamWriter sw = p.StandardInput;
        StreamReader sr = p.StandardOutput;

        char[] buffer = new char[1024];
        int l = 0;

        sw.Write("DEVCON ReScan");
        sw.Write(sw.NewLine);

        Console.Write(">> ");

        l = sr.Read(buffer, 0, buffer.Length);

        for (int n = 0; n < l; n++)
            Console.Write(buffer[n] + " ");

        p.Close();