Reputation: 301
I´m having a little problem with my application. With my application I want to download some files via webclient.DownloadFileAsync and in case the user quits the program while a download is still running, I want to cancel that webclient-process & delete the file as well.
I already tried it with the following code, but it´s not quite working as I´m always getting a IOException (file in use by other process).
for (z = 0; z < CheckedCount; z++)
{
MultiWebclient[z].CancelAsync();
MultiWebclient[z].Dispose();
dgvDownloads.Rows[z].Cells[5].Value = "Canceled";
File.Delete(selectedFolder + _downloadRowNameList[z] + ".mp4");
}
Upvotes: 1
Views: 1432
Reputation: 301
I´m not sure if this is a legit solution, but I managed to solve my problem by canceling the webclient (webclient.CancelAsync();) with an extra button and by putting the File.Delete(); inside an if(e.Cancelled)-statement which will be fired in the DownloadFileCompleted-event.
Upvotes: 0
Reputation: 612
Your MultiWebClient probably still has the file open in a stream. What does that Dispose method really do? I guess it's also possible that Dispose method may do some work asynchronously and your stream is still open when it gets to that file. The bottom line is something somewhere has that file and the big suspect there is that MultiWebClient.
Upvotes: 0
Reputation: 148120
The downloading files are attached with downloading routine and when you try to delete these files you get the error. There are few things you can try.
Use timer to repeatedly check if the file handles are released by the download routine, you may check after 30 seconds. This way you will be able to delete files as soon as the handle is released by downloading routine.
You may store paths/filenames of the files to delete when user cancels the operation and delete files on next application start.
Upvotes: 1