Hello,
I have a class which executes a Process (runs a command line command). On receiving the output from the command execution, I want to check various lines and throw exception. My code is :
************ This is a library class
public int ConnectToServer()
{
int error = 0;
connected = false;
try
{
process = Process.Start(processInfo);
process.BeginOutputReadLine();
process.OutputDataReceived += new DataReceivedEventHandler(Process_OutputDataReceived);
}
catch (Exception e)
{
Console.WriteLine("Error Processing ConnectToServer : " + e.Message);
errorMsg = e.Message;
error = -1;
}
return error;
}
private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
string d = e.Data;
Console.WriteLine("LINE = " + d);
if (d != null)
{
if (d.IndexOf("Completed") > 0)
{
connected = true;
Console.WriteLine("********* Connected = " + connected);
}
else if (isInValidLine(d))
throw new Exception(d);
}
return;
}
private bool isInValidLine(string line)
{
if (line.IndexOf("Cannot load file") > 0)
return true;
return false;
}
GUI CODE where I am calling it :
***************************
try
{
StartConnect();
}
catch (Exception ex)
{
string msg = ex.Message;
if (msg.Equals("NotConnectedException"))
MessageBox.Show("Error connecting : Connection Time Out "Time Out", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
else if (msg.IndexOf("Cannot load file") > 0)
MessageBox.Show("Error connecting : Problem with File \n Unable to Load or Find required file.", "Failed to Connect", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
private void StartConnect()
{
DateTime start = DateTime.Now;
int timeout = 40000, timepassed = 0;
oc = new OpenConnect(cmd, timeout);
int retVal = oc.ConnectToServer();
while (!oc.Connected)
{
timepassed = (int)(DateTime.Now - start).TotalMilliseconds;
if (timepassed > timeout)
{
connectedToVpn = false;
throw new Exception("NotConnectedException");
}
Thread.Sleep(100);
}
Can anyone help me solve the mistake? What I want is the Exception that are thrown in Process_OutputDataReceived should be handled in ConnectToServer() or handled in try{} that calls StartConnect().
Why do I get a runtime Exception at throw @ new Exception("Cannot find file") line?
Any help is appreciated. I am stuck up want to handle such many cases by reading the output of the command.
Thanks