I asked a question previously to cancel the process of compressing files.
I have 2 problems with this code, the program has the function of compressing files in pairs separately getting 2 files in each 7z, the files are bin, cue using 7z, I have a folder full of these files and wanted to compress them
The problems are:
When I run the program and click cancel the program but 7z is still working.
public partial class Form1 : Form, IProgress<int>
{
private CancellationTokenSource _cancellation;
public Form1()
{
InitializeComponent();
}
private void ZipFiles(IList<string> files, IProgress<int> progress, CancellationToken token)
{
Process x;
Process Zip(string file)
{
string game = Path.ChangeExtension(file, null) + ".7z";
string cue = Path.ChangeExtension(file, ".cue");
x = new Process()
{
EnableRaisingEvents = true,
StartInfo = new ProcessStartInfo
{
FileName = "7z.exe",
Arguments = String.Format("a -t7z \"{0}\" \"{1}\" \"{2}\" -mx=9", game, file, cue),
WindowStyle = ProcessWindowStyle.Hidden
}
};
x.Start();
return x;
}
var count = 0;
void Handler(object o, EventArgs a)
{
var p = o as Process;
if (_cancellation.Token.IsCancellationRequested)
{
x.Close();
x.Kill();
return;
}
if (count < files.Count)
{
var next = Zip(files[count]);
count++;
next.Exited += Handler;
}
progress.Report(count * 100 / files.Count);
p.Exited -= Handler;
}
{
var process = Zip(files[count]);
process.Exited += Handler;
}
}
public void Report(int value)
{
Invoke((Action)(() =>
{
progressBar.Value = value;
if (value == 100)
{
btnZip.Enabled = true;
}
}));
}
private void btnZip_Click(object sender, EventArgs e)
{
btnZip.Enabled = false;
_cancellation = new CancellationTokenSource();
var files = Directory.EnumerateFiles(@"C:\Users\Fabyo.GALUTTI\Desktop\p", "*.bin", SearchOption.AllDirectories)
.Take(100)
.ToList();
ZipFiles(files, this, _cancellation.Token);
}
private void btnCancel_Click(object sender, EventArgs e)
{
_cancellation.Cancel();
progressBar.Value = 0;
btnZip.Enabled = true;
}
}