代码之家  ›  专栏  ›  技术社区  ›  callisto

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

  •  3
  • callisto  · 技术社区  · 17 年前

    我需要做两件事:运行一个批处理文件(工作正常),运行一个命令(不工作)。 命令的方法引发异常“找不到文件”。如果我打开一个命令窗口,然后键入命令,它就会工作得很好。

      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 回复  |  直到 17 年前
        1
  •  9
  •   OregonGhost    17 年前

    DEVCON ReScan 是否确实是可执行文件的名称?我猜可执行文件是devcon,而rescan是一个参数。这意味着您必须将startinfo.filename设置为“devcon”,将startinfo.arguments设置为“rescan”。

        2
  •  0
  •   Led    17 年前

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

    此外,您必须指定扩展名,所以我想您应该使用“devcon.exe”, 并指定不在文件名中但在参数中的参数:)

        3
  •  0
  •   TheVillageIdiot    17 年前

    试试这个:

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