【问题标题】:c# Process.Start with credentials always "access is denied" when running in WPF application, Console is working finec# Process.Start with credentials 在 WPF 应用程序中运行时总是“拒绝访问”,控制台工作正常
【发布时间】:2021-09-02 14:26:26
【问题描述】:

我正在启动一个外部可执行文件(作为项目解决方案的一部分提供)以获取控制台输出,以便事后分析结果。一切正常,当我使用控制台应用程序使用 Process.Start 启动进程时,使用以下代码:

System.Diagnostics.Process proc = new System.Diagnostics.Process();

proc.StartInfo.FileName = $"{location}find.exe"; // External EXE!
proc.StartInfo.Arguments = $"\"{host}\" -printf \"%M %p\n\"";

// Set credentials
proc.StartInfo.Domain = domain;
proc.StartInfo.UserName = username;

System.Security.SecureString ssPwd = new System.Security.SecureString();
for (int x = 0; x < password.Length; x++)
{
    ssPwd.AppendChar(password[x]);
}
proc.StartInfo.Password = ssPwd;

// StartInfo setup
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.CreateNoWindow = true;
proc.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
proc.ErrorDataReceived += new DataReceivedEventHandler(OutputErrorHandler);

proc.Start();  // <--- System.ComponentModel.Win32Exception occures on calling Start()
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
proc.WaitForExit();

将确切的代码添加到我的 WPF 应用程序后,它总是抛出一个异常,说“访问被拒绝”。同样,在使用管理员权限运行 WPF 应用程序时,也会发生同样的错误。

但是它在 WPF 中工作,如果我取出凭据,但它在本地用户下运行,应该避免什么。相反,应该使用给定的凭据来启动该过程。

WPF 应用程序有什么不同?我错过了什么吗?

任何提示表示赞赏...

注意编辑:

我在 github 上添加了一个 repo,它也按预期工作。 包含的来自 codeproject 的模拟工作不正常(在我的情况下),但 Process.Start with credentials 现在在 WPF 中工作正常......

需要深入挖掘我当前的项目...

回购链接: CSharp-Impersonation-Example

【问题讨论】:

  • 哪行代码抛出异常?
  • @Robert Harvey:通过调用 Start() 函数(代码示例中添加了注释)
  • 我在这里也找到了一篇好文章:weblogs.asp.net/hernandl/startprocessasuser
  • 您是管理员吗?除非您通过右键单击快捷方式启动 VS 并选择以管理员身份运行,否则 VS 不会启用管理员。
  • VS 总是以管理员启动(在我的情况下,因为我也在使用本地 IIS 进行开发)。 CMD和WPF都是在同一个项目中运行的,所以情况是一样的。此外,对于 Admin,WPF 会出现“访问被拒绝”消息。

标签: c# .net process processstartinfo


【解决方案1】:

有一些与 UseShellExecute 相关的重大更改,当从 WPF 启动进程时应该将其设置为 true - 但是我不确定重定向是否会起作用(也许还有凭据)?你可以尝试将其设置为true并尝试一下吗?

【讨论】:

  • 感谢您的回复。我得到 -> System.InvalidOperationException: 'Process 对象必须将 UseShellExecute 属性设置为 false 才能以用户身份启动进程。'
  • 如果您注释掉域、用户名和密码 - 在当前凭据下运行会发生什么?
  • CMD 也运行良好,但使用本地用户的凭据。如果没有这些设置,WPF 也可以正常工作...
  • Per MS:如果提供了 UserName 和 Password,则必须设置 WorkingDirectory 属性。如果未设置该属性,则默认工作目录为 %SYSTEMROOT%\system32。所以这可能是问题所在。
  • 并且 find.exe 存在于 %SYSTEMROOT%\system32
猜你喜欢
  • 1970-01-01
  • 2015-09-20
  • 1970-01-01
  • 1970-01-01
  • 2019-04-01
  • 2013-11-07
  • 2016-12-15
  • 2021-06-19
  • 1970-01-01
相关资源
最近更新 更多