我们什么时候需要将UseShellExecute设置为True?

xpo*_*ort 121 c#

//
// Summary:
//     Gets or sets a value indicating whether to use the operating system shell
//     to start the process.
//
// Returns:
//     true to use the shell when starting the process; otherwise, the process is
//     created directly from the executable file. The default is true.
[DefaultValue(true)]
[MonitoringDescription("ProcessUseShellExecute")]
[NotifyParentProperty(true)]
public bool UseShellExecute { get; set; }
Run Code Online (Sandbox Code Playgroud)

如果我们生成一个新进程,我们什么时候需要将UseShellExecute设置为True?

Jus*_*tin 188

UseShellExecute布尔属性是关系到使用的Windows ShellExecute的功能VS的CreateProcess的功能-简单的答案是,如果UseShellExecute为真,那么Process类将使用该ShellExecute功能,否则它会使用CreateProcess.

更长的答案是该ShellExecute函数用于打开指定的程序或文件 - 它大致相当于在执行对话框中键入要执行的命令并单击OK,这意味着它可以用于(例如):

  • 使用默认浏览器打开.html文件或Web,无需知道浏览器是什么,
  • 打开word文档而无需知道Word的安装路径是什么
  • 运行批处理文件
  • 在上运行任何命令 PATH

例如:

Process p = new Process();
p.StartInfo.UseShellExecute = true;
p.StartInfo.FileName = "www.google.co.uk";
p.Start();
Run Code Online (Sandbox Code Playgroud)

它非常易于使用,功能多样且功能强大,但有一些缺点:

  • 无法重定向标准输入/输出/错误句柄
  • 不可能为子进程指定安全描述符(或其他很酷的东西)
  • 如果您对实际运行的内容做出假设,则可能会引入安全漏洞:

    // If there is an executable called "notepad.exe" somewhere on the path 
    // then this might not do what we expect
    p.StartInfo.FileName = "notepad.exe";
    p.Start();
    
    Run Code Online (Sandbox Code Playgroud)

CreateProcess是一种更加精确的启动流程的方法 - 它不会搜索路径并允许您重定向子流程的标准输入或输出(以及其他内容).CreateProcess然而,缺点是上面给出的4个例子都不起作用(试试看).

总之,UseShellExecute如果符合以下条件,则应设置为false:

  • 您想重定向标准输入/输出/错误(这是最常见的原因)
  • 您不希望搜索可执行文件的路径(例如出于安全原因)

相反,UseShellExecute如果要打开文档,URL或批处理文件等,则应该保持正确...而不必显式提供可执行文件的路径.

  • 另外,你说当'UseShellExecute = false`即CreateProcess时,不会检查路径,但我看到即使我做"UseShellExecute = false"即假设没有检查路径,那么process.FileName ="cmd.exe "这样可以检查c:\ windows\system32.如果我将cmd.exe复制到c:\ windows并将其命名为cmmmd.exe,那么我会执行process1.FileName ="cmmmd.exe",因为它检查c:\ windows所以它似乎正在检查路径,或者一些目录. (4认同)
  • 很棒的东西,但你写的(使用ShellExecute),"它[你声称]是不可能重定向标准输入/输出/错误句柄"< - 当然是不正确或不准确.即使将useShellExecute设置为true,虽然你确实不能做`processStartInfo.RedirectStandardOutput = true`,但在我看来你仍然可以通过`process.Arguments ="cmd/c dir> c:\\ crp来重定向标准输出. \\ AA"`.同样,从运行对话框中可以执行`cmd/c dir> c:\ crp\aa` (2认同)
  • MSDN文档同意@barlop:"当UseShellExecute为false时,FileName属性可以是可执行文件的完全限定路径,也可以是系统将尝试在PATH环境变量指定的文件夹中查找的简单可执行文件名称." (2认同)
  • 通过将“UseShellExecute”设置为“true”,我能够共享一个环境变量(仅在调用进程中创建)。非常便利 (2认同)

Bal*_*a R 14

我认为主要是针对非可执行文件.例如,如果您尝试打开.html文件,则必须设置UseShellExecutetrue,并且将在用户设置为默认的浏览器中打开.html.


Che*_*hen 11

来自MSDN:

将此属性设置为false可以重定向输入,输出和错误流.

如果UserName属性不为null或为空字符串,则UseShellExecute必须为false,否则在调用Process.Start(ProcessStartInfo)方法时将抛出InvalidOperationException.

使用操作系统shell启动进程时,可以启动任何文档(与具有默认打开操作的可执行文件关联的任何已注册文件类型),并使用Process组件对文件执行操作(如打印).当UseShellExecute为false时,您只能使用Process组件启动可执行文件.

如果将ErrorDialog属性设置为true,则UseShellExecute必须为true.