我目前正在构建一个简单的应用程序,它启动openvpn.exe
。但是,openvpn.exe
会要求输入用户名和密码。
但是,当发生这种情况时,我的程序不读取字符串,它只是等待CMD关闭然后继续使用代码。因此,它会一直阻塞,直到窗口关闭。
有没有办法绕过这个?我的代码如下:
void button_Connect_Click(object sender, EventArgs e)
{
var proc = new Process();
proc.StartInfo.FileName = @"C:\Program Files (x86)\OpenVPN\bin\openvpn.exe";
proc.StartInfo.Arguments = "--config config.ovpn --auto-proxy";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.WorkingDirectory = @"C:\Program Files (x86)\OpenVPN\bin";
// set up output redirection
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
// Input
proc.StartInfo.RedirectStandardInput = true;
// Other
proc.EnableRaisingEvents = true;
proc.StartInfo.CreateNoWindow = false;
// see below for output handler
proc.ErrorDataReceived += proc_DataReceived;
proc.OutputDataReceived += proc_DataReceived;
proc.Start();
myStreamWriter = proc.StandardInput;
proc.BeginErrorReadLine();
proc.BeginOutputReadLine();
proc.WaitForExit();
}
void proc_DataReceived(object sender, DataReceivedEventArgs e)
{
// output will be in string e.Data
if (e.Data != null)
{
string Data = e.Data.ToString();
if (Data.Contains("Enter Auth Username"))
{
this.myStreamWriter.WriteLine("myinput");
}
}
}
答案 0 :(得分:0)
新行会触发proc_DataReceived
。假设密码是控制台应用程序要求的唯一输入,您可以在启动该过程后立即将其发送到myStreamWriter
。它将在必要时进行缓冲和消费。