I’m making a program that downloads a photo from the internet and saves it to a file called “temp.jpg”. My program user BackgroundWorker and I have a problem for example, the second time I run the BackgroundWorker my program tries to open “temp.jpg” but it’s still being using by the first BackgroundWorker.
Any advice how to solve this?
A solution could be naming the file by a timestamp or something like that.
To donwload the photo to temp.jpg I’m using
WebClient webClient = new WebClient();
try
{
webClient.DownloadFile(foto, path);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
the problem is that “temp.jpg” is being used by the first BackgroundWorker.
EDIT
WebClient.DownloadFilehandles the management of the file stream for you so, this is not a problem with your disposal of stream objects or release of file handles.You need to ensure that each concurrent call to
WebClient.DownloadFileis using a unique filename.Unique temporary file names can be generated by the framework using the
Path.GetTemporaryFileNamemethod.You should ensure you are closing the the files and releasing the handle in you background worker, this is generally achecived with a
usingblock around theIDisposablefile stream.If you want to download files concurrently i.e. on multiple background workers at once, then each worker will need a unique file name but, if this is a problem for a repeated run of a single background worker, unique names is not the right solution. Hiding the problem by using new unique filenames will just leak resources.