【发布时间】:2012-12-14 14:26:43
【问题描述】:
我正在学习 C#,我正在创建一个简单的 WinForms 应用程序,它的作用是启动一个简单的 OpenVPN 客户端:
void button_Connect_Click(object sender, EventArgs e)
{
var proc = new Process();
proc.StartInfo.FileName = "CMD.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.WorkingDirectory = @"C:\Program Files (x86)\OpenVPN\bin";
proc.StartInfo.Arguments = "/c openvpn.exe --config config.ovpn --auto-proxy";
// 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();
StreamWriter 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"))
{
myStreamWriter("myusername");
}
//MessageBox.Show(Data);
}
}
它现在所做的是将 CMD 的所有输出发送到我的程序,该程序根据输出运行命令。
我当前的问题是,我需要写入流。我在proc_DataReceived 中使用myStreamWriter,但是它不在同一个上下文中,所以它不起作用。
我收到以下错误:The name 'myStreamWriter' does not exist in the current context,该范围内显然不存在。
我该如何进行这项工作?获取/设置属性?就像我说的那样,我对 C# 很陌生,因此感谢您提供任何帮助。
【问题讨论】:
-
我认为您正在寻找“范围”而不是“上下文”这个词;)。
-
你为什么要开始
cmd.exe而不仅仅是openvpn.exe? -
@tomfanning 因为我需要写入 cmd 进程。刚打开
openvpn.exe时不起作用。 -
@Devator “不起作用”是什么意思?它会抛出空引用错误吗?
-
@Devator,那是因为您已将
UseShellExecute设置为false
标签: c# winforms conventions