Emetrop
Emetrop

Reputation: 322

Locked file while second work

I have a code which is similar this:

string path = "img.jpg";
byte[] file = File.ReadAllBytes(path);

//...

using (WebClient client = new WebClient())
{
    client.DownloadFile(new Uri(@"http://www....com/img.jpg"), path);
}

But on the line with DownloadFile it throws exception

The process cannot access the file .../img.jpg because it is being used by another process.

everytime. What's wrong?

Upvotes: 0

Views: 63

Answers (1)

Mauricio Gracia Gutierrez
Mauricio Gracia Gutierrez

Reputation: 10844

To have more control over what is happening change that using to a try/catch

try
{
    WebClient client = new WebClient()
    client.DownloadFile(new Uri(@"http://www....com/img.jpg"), path);
}
catch (Excepcion ex)
{
    //Debug here or set the text of some control to ex.Message to see what is causing the problem
}
finally
{
    //dispose client
}

UPDATE

Is probably your own process that is keeping a reference to that file.

What is the point to read all the bytes of your local file and then replace that file with and image from the web. I think you only need to do one of those

Upvotes: 2

Related Questions