My C#
program runs a process that starts a command prompt application passing in arguments to it, when the specific button is clicked.
the program gets a directory path from the user selection, and checks to see if it is empty.
If it is not empty the for each loop will loop through the array of full paths to each file in the directory. It will also set a progress bar to 0 and ready it for incrementation
As it loops through it will run the
cli-task
using Process
Here is the problem: Upon completion of the task of looping through the file I want it to delete the file and increment the progress bar.
This works fine if do have it go through one by one like this:
process.WaitForExit(10000);
File.Delete(fileName);
progressBar1.Increment(1);
but the program is incredibly slow. as it waits for each process to complete before it starts the next one.
So I then attempted the code below:
string[] files = Directory.GetFiles(label1.Text);
if (files.Length != 0)
{
progressBar1.Value = 0;
progressBar1.Minimum = 0;
progressBar1.Maximum = files.Length;
foreach (string fileName in files)
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
//startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = @"C:\Program Files\cli-tool\cli.exe";
startInfo.Arguments = "-i " + "\"" + fileName + "\"" + " -o " + "\"" + label2.Text + "\\" + Path.GetFileName(fileName) + "\"" + " -s -t";
process.StartInfo = startInfo;
process.EnableRaisingEvents = true;
process.Start();
process.Exited += delegate
{
File.Delete(fileName);
progressBar1.Increment(1);
};
}
Unfortunately when I run it this way it crashes the program when it gets to the File.Delete(fileName)
part, but the original process.start
task works, but it is able to remove the first file of the first process that exited it looks like.
the following error is shown in the debug console of visual studio:
A first chance exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll The program '[3308] IonicFolderProtector.vshost.exe: Managed (v4.0.30319)' has exited with code 0 (0x0).
I cannot determine what is wrong with this code.
Am I wrong to think that process.Exited += delegate { // some code };
will run each time as each process that is created at the same time?