Monday, December 6, 2010

Run Process from ASPNET and capture output

ProcessStartInfo myProcessInfo = new ProcessStartInfo();
myProcessInfo.WorkingDirectory = workingDir; //variable with folder to be on
myProcessInfo.FileName = file; //file to run
myProcessInfo.Arguments = args; //arguments: string, spaces between args

Process myProcess = new Process();
myProcess .StartInfo = myProcessInfo;
gerador.Start();
myProcess.PriorityClass = ProcessPriorityClass.RealTime; //must be after starting!

gerador.WaitForExit(600000); //max waiting for 10 minutes
if (!gerador.HasExited)
{
gerador.Kill();
}

TimeSpan durationInSeconds = (DateTime.Now - gerador.StartTime).Seconds.ToString();
textDuration.Text = "Duration: " + durationInSeconds + " seconds!";

optionally set on exit action
//myProcess .Exited += delegate { Response.Write("Finished in "+(DateTime.Now - gerador.StartTime).Seconds.ToString() + " seconds"); };

or on exit event
myProcess .EnableRaisingEvents = true;
myProcess .Exited += new EventHandler(procExit);

void procExit(object sender, EventArgs e)
{
//DO STUFF
}

//for output
//myProcessInfo.RedirectStandardOutput = true;
//myProcessInfo.UseShellExecute = false;
//myProcessInfo.CreateNoWindow = true;
//myProcessInfo.ErrorDialog = false;
//StreamReader read = myProcess.StandardOutput;
//if (myProcess.HasExited)
//{
// string res = read.ReadToEnd();
// read.Close();
// Response.Write(res);
//}

1 comment:

  1. Estas sempre a colocar o código!! Já começas a escrever um bocadinho para se entender...

    ReplyDelete