I'm learning C# and I'm creating a simple WinForms application, and what it does is starting a simple OpenVPN client:
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);
}
}
What it does now, is send all the output of the CMD to my program, which run commands depending on the output.
My current issue is, I need to write to the stream. I use myStreamWriter
in proc_DataReceived
, however it's not in the same context so it doesn't work.
I get the following error: The name 'myStreamWriter' does not exist in the current context
, which is obviously non existent in that scope.
How do I make this work? Get/set properties? Like I said I'm quite new to C# so any help is appreciated.