【发布时间】:2017-07-15 04:08:13
【问题描述】:
我在使用 C# 以编程方式将输入传递给系统 net user 程序时遇到问题。我正在尝试为某个用户帐户激活并设置密码。根据我的调查,似乎该过程在任何事情都可以通过之前就完成了。不知道为什么后台net user程序不等待输入才退出。
这是我以编程方式运行的命令:
net user username /active:yes & net user username *
第二条命令的输出如下:
Type a password for the user:
Retype the password to confirm:
The command completed successfully
如果您要手动运行上述命令,它会要求您输入密码并从屏幕上隐藏您正在输入的内容。但是,程序在以编程方式运行时似乎并没有停止。
为了调用程序,我有一个函数,它启动程序并将进程返回给另一个函数,该函数将输入发送到进程。这是第一个函数:
static Process RunCommandGetProcess(string command)
{
Process process = new Process();
ProcessStartInfo psInfo = new ProcessStartInfo();
psInfo.FileName = "CMD.exe";
psInfo.Arguments = "/C " + command + "& PAUSE";
// Allow for Input redirection
psInfo.UseShellExecute = false;
psInfo.RedirectStandardInput = true;
// Window style
psInfo.WindowStyle = ProcessWindowStyle.Normal;
// Start the mothertrucker!
process.StartInfo = psInfo;
process.Start();
return process;
}
以及调用函数:
static int ActivateUserWithPassword(string password)
{
// Start net user with that other function
Process process = RunCommandGetProcess("net user username /active:yes & net user username *");
StreamWriter streamWriter = process.StandardInput;
streamWriter.WriteLine(password); // First Prompt
streamWriter.WriteLine(password); // Second Prompt
process.WaitForExit();
return process.ExitCode;
}
但是,当我运行调试器时,命令在两条streamWriter.WriteLine(password); 行之前成功完成!我试过谷歌搜索,但无济于事。
你们是我唯一的希望。
【问题讨论】:
-
我认为你的命令不等待密码,启动后立即结束。您可以通过手动运行命令来检查这一点吗?
-
@Dmitry 最后是一个错字吗?当我运行调试器并在两个
WriteLine处放置断点时,该命令在没有输入的情况下完成执行,甚至在它到达它之前。虽然。我可能无意中将输入发送到第一个命令,而断点只是未对齐它们。 -
@MasonSchmidgall 查看我的解决方案,如果它有效,请告诉我。