从Visual Studio打开的CMD提示符不能在我的计算机上启动exe.为什么不

本文关键字:计算机 我的 启动 为什么不 exe 不能 提示符 Studio Visual CMD | 更新日期: 2023-09-27 18:17:28

我有下面的代码来启动cmd提示符,并从cmd提示符启动putty.exe,并在末尾显示IP地址。

private void btnRouter_Click(Object sender, EventArgs e)
{
    MessageBox.Show((string)((Button)sender).Tag);
    System.Diagnostics.Process cmd = new System.Diagnostics.Process();
    cmd.StartInfo.FileName = @"C:'windows'system32'cmd.exe";
    cmd.StartInfo.UseShellExecute = true;
    cmd.Start();
    cmd.StandardInput.WriteLine("Putty.exe " + ((string)((Button)sender).Tag));
    cmd.WaitForExit();
}

问题是我一直得到一个错误"StandardIn没有被重定向。"从Visual Studio,当我尝试在启动的命令窗口中输入putty.exe,我得到"'putty.exe'无法识别为内部或外部命令,这真的很奇怪,因为如果我去运行行,输入cmd,然后putty.exe,它立即打开,因为我添加了绝对文件夹路径到putty应用程序到我的系统环境路径。

是否有原因从Visual Studio打开的CMD不使用我的环境路径?

仍然不知道为什么会发生,但是我回到以前的一些代码,并在我的调试文件夹中放了一个putty.exe的副本,这次它成功启动了。

private void btnRouter_Click(Object sender, EventArgs e)
{
    MessageBox.Show((string)((Button)sender).Tag);
    System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
    startInfo.FileName = "Putty.exe ";
    startInfo.Arguments = ((string)((Button)sender).Tag);
    myProcess.StartInfo = startInfo;
    myProcess.Start();
}

从Visual Studio打开的CMD提示符不能在我的计算机上启动exe.为什么不

这一行将导致"StandardIn未被重定向"。由于您试图写入stdin而该句柄未正确设置输入而导致的错误:

cmd.StandardInput.WriteLine("Putty.exe " + ((string)((Button)sender).Tag));

关于这个问题:

是否有原因从Visual Studio打开的CMD不使用我的环境路径?

当父进程启动子进程时,子进程将继承其父进程的环境。

换句话说,您启动的新cmd窗口将继承Visual Studio环境的,但这并不意味着Visual Studio环境与命令提示符环境相同。

您可以通过启动命令行提示符,从该命令行提示符运行Visual Studio,然后创建子cmd进程来测试这一点。

现在你的cmd进程应该有一个与原始命令行以及Visual Studio在其环境副本中添加的任何更改相匹配的环境。

使用runas命令。

http://technet.microsoft.com/en-us/library/cc771525.aspx