Wednesday, May 29, 2013

Defrag Output in C#

Sorry if this has been posted somewhere before, but I have several problems when trying to use the Windows disk defragmenter in C#.


I would like to run the defrag.exe process from within my application, and show real-time feedback.


I have written something like the code below:



private void defragAction(object sender, RoutedEventArgs e)
{
System.Threading.Thread workT = new System.Threading.Thread(new System.Threading.ThreadStart(new Action(
delegate
{
System.Diagnostics.Process defragProcess = new Process();

defragProcess.StartInfo.FileName = "defrag.exe";
string letter = curInfo.Name.Substring(0, 1).ToUpper();
defragProcess.StartInfo.Arguments = letter + @": -f";
defragProcess.StartInfo.RedirectStandardInput = true;
defragProcess.StartInfo.RedirectStandardOutput = true;
defragProcess.StartInfo.UseShellExecute = false;
defragProcess.StartInfo.CreateNoWindow = true;
defragProcess.EnableRaisingEvents = true;
defragProcess.OutputDataReceived += defragOutputRecieved;
defragProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal;

defragProcess.Start();
defragProcess.BeginOutputReadLine();
}
)));
workT.Start();




I then have another method to recieve the output:


private void defragOutputRecieved(object sender, DataReceivedEventArgs e)
{
Application.Current.Dispatcher.Invoke(new Action(
delegate
{
MessageBox.Show(e.Data);
}));
}

The problem is that the output stream is only read when the defrag process has finished or is cancelled. I need real-time user feedback in my application.


I don't understand as Process.BeginOutputReadLine() is supposed to be an asynchronous operation.


Has anyone got any suggestions on how I can make this work?


Thanks.


No comments:

Post a Comment