C# 如何从代码运行命令行命令
我需要做两件事:运行批处理文件(工作正常)和运行命令(不工作)。 该命令的方法引发异常“未找到文件”。如果我打开一个cmd窗口,并键入命令,它就可以正常工作C# 如何从代码运行命令行命令,c#,.net,command-line,batch-file,C#,.net,Command Line,Batch File,我需要做两件事:运行批处理文件(工作正常)和运行命令(不工作)。 该命令的方法引发异常“未找到文件”。如果我打开一个cmd窗口,并键入命令,它就可以正常工作 private static void Rescan() { //System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("DEVCON ReScan"); //psi.RedirectSt
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);
}
}
注释后的代码也会引发相同的异常。
DEVCON ReScan
真的是可执行文件的名称吗?我猜可执行文件是DEVCON,而ReScan是一个参数。这意味着您必须将StartInfo.FileName设置为“DEVCON”,将StartInfo.Arguments设置为“ReScan”。DEVCON应用程序实际是否在工作目录中?
否则,除非指定它的完整路径,否则它将无法工作
此外,您必须指定扩展名,因此我想您应该选择“Devcon.exe”,
并不是在文件名中指定参数,而是在参数中指定:)尝试以下操作:
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();
ProcessStartInfo psi=new ProcessStartInfo();
psi.FileName=Environment.GetEnvironmentVariable(“comspec”);
psi.CreateNoWindow=真;
psi.error=true;
psi.INPUT=真;
psi.0输出=真;
psi.UseShellExecute=false;
过程p=过程启动(psi);
ConsoleColor fc=Console.ForegroundColor;
StreamWriter sw=p.StandardInput;
StreamReader sr=p.StandardOutput;
char[]buffer=新字符[1024];
int l=0;
软件写入(“DEVCON重新扫描”);
sw.Write(sw.NewLine);
控制台。写入(“>>”;
l=sr.Read(缓冲区,0,缓冲区长度);
对于(int n=0;n
出于一些有趣的原因,这是System.Diagnostics.Process和本机ShellExecute(Ex)中的一个常见错误,尽管它显然是一个“FileName”参数:)我会将FileName设置为FileName(devcon.exe),并使用proc.StartInfo.Arguments传入重新扫描参数。只是为了让大家明白什么是什么。我在使用进程时经常做同样的事情(这不是经常做的)…Devcon位于PATH环境目录中。它正在工作:proc.StartInfo.FileName=“DEVCON”;proc.StartInfo.Arguments=“重新扫描”;