第二次工作时锁定文件

时间:2013-12-26 00:22:23

标签: c# webclient

我有一个类似的代码:

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

//...

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

但是在DownloadFile的行上它会抛出异常

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

每次。怎么了?

1 个答案:

答案 0 :(得分:2)

要更好地控制usingtry/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
}

<强>更新

可能是您自己的进程保留对该文件的引用。

读取本地文件的所有字节然后用web替换该文件和图像有什么意义。我想你只需要做其中一个

相关问题