C# .NET 进程使用凭据启动进程错误(句柄无效)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/628191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 10:54:41  来源:igfitidea点击:

.NET Process Start Process Error using credentials (The handle is invalid)

c#.netsystem.diagnostics

提问by Cyberherbalist

I have an Windows Form application that supplies the User Name, Domain, and Password to the StartInfo, and it throws this:

我有一个 Windows 窗体应用程序,它为 StartInfo 提供用户名、域和密码,它抛出以下内容:

System.ComponentModel.Win32Exception: The handle is invalidat System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo) at System.Diagnostics.Process.Start()

System.ComponentModel.Win32Exception:句柄在 System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo) 处无效,位于 System.Diagnostics.Process.Start()

When I allow the credentials to default to current user I get no such error, and the process I start works to the extent that it doesn't need to use credentials (the creds are necessary for mapping a drive in an MSBuild script). Here's the code that fills the start info:

当我允许凭据默认为当前用户时,我不会收到此类错误,并且我开始的过程在不需要使用凭据的范围内有效(凭据是在 MSBuild 脚本中映射驱动器所必需的)。这是填充开始信息的代码:

Process p = new Process();
ProcessStartInfo si = new ProcessStartInfo(buildApp, buildArgs);
si.WorkingDirectory = msBuildWorkingDir;
si.UserName = txtUserName.Text;
char[] psw = txtPassword.Text.ToCharArray();
SecureString ss = new SecureString();
for (int x = 0; x < psw.Length; x++)
{
    ss.AppendChar(psw[x]);
}
si.Password = ss;
si.Domain = "ABC";
si.RedirectStandardOutput = true;
si.UseShellExecute = false;
si.WorkingDirectory = txtWorkingDir.Text;
p.StartInfo = si;
p.Start();

It isn't that the user/psw isn't matching, because when I provide a bad psw, for example, it catches it. So, this "invalid handle" thing is happening after the cred is passed. Any ideas on what I might be omitting or screwing up?

并不是用户/密码不匹配,因为例如,当我提供一个错误的密码时,它会捕获它。所以,这个“无效句柄”的事情发生在信用通过之后。关于我可能遗漏或搞砸的任何想法?

采纳答案by NotMe

You have to redirect your Input, Error, and Output.

您必须重定向输入、错误和输出。

for example:

例如:

ProcessStartInfo info = new ProcessStartInfo("cmd.exe");
 info.UseShellExecute = false;
 info.RedirectStandardInput = true;
 info.RedirectStandardError = true;
 info.RedirectStandardOutput = true;
 info.UserName = dialog.User;

 using (Process install = Process.Start(info)) {
       string output = install.StandardOutput.ReadToEnd();
       install.WaitForExit();
       // Do something with you output data       
    Console.WriteLine(output);
 }

Also microsoft has said the error should read, "Unable to redirect input." (used to have a link, but that no longer worked)

微软还表示错误应该是“无法重定向输入”。(曾经有一个链接,但不再有效)