【发布时间】:2019-04-18 11:08:13
【问题描述】:
我正在尝试使用 System.Diagnostics.Process 命名空间在 C# 程序中调用 chrome.exe。
我的 chrome.exe 位于路径 C:\Program Files (x86)\Google\Chrome\Application
如果我通过传递以下参数调用 RunProc 函数 - (保持 exe 的绝对路径并保持 WorkingDirectory 为空)
("C:\Program Files (x86)\Google\Chrome\Application\Chrome.exe" , "https://www.google.com", "") 它工作得很好。
但是,有参数 -
("Chrome.exe , "https://www.google.com", "C:\Program Files (x86)\Google\Chrome\Application") 它在步骤 proc.Start 处给出异常(); 说明 - 系统找不到指定的文件。
我还尝试在初始化 StartInfo 时编写 WorkingDirectory = workingDir,但仍在寻找解决方案。
class Program
{
static void Main(string[] args)
{
RunProc(@"chrome.exe", @"https://www.google.com", @"C:\Program Files (x86)\Google\Chrome\Application");
}
static bool RunProc(string exe, string args, string workingDir)
{
Process proc = new Process
{
StartInfo =
{
FileName = exe,
CreateNoWindow = true,
RedirectStandardInput = true,
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
Arguments = args,
//WorkingDirectory = workingDir
}
};
if (!string.IsNullOrEmpty(workingDir))
{
proc.StartInfo.WorkingDirectory = workingDir;
}
proc.Start();
proc.StandardInput.WriteLine(args);
proc.StandardInput.Flush();
proc.StandardInput.Close();
return true;
}
}
【问题讨论】:
-
如果您能提供minimal reproducible example,那就太好了,这样我们就可以在代码中看到您是如何调用该方法的(以及使用哪些参数)。
-
使用这一行:
FileName = exe,exe是否包含您要启动的文件的完整路径,或者只是文件名?工作目录不用于执行文件 -
变量 exe 仅包含文件名。我想设置文件所在的工作目录。如果该文件在您的工作中直接可用,那么您应该只能使用名称运行 exe。
-
@mjwills - 我已经更新了这个问题,给出了完整的工作代码和一个例子。希望这会有所帮助。
标签: c# process system.diagnostics