webclient无法使用文件(由另一个进程使用..)

时间:2013-12-23 17:11:45

标签: c# .net winforms

好的...这段代码的一部分MOST LIKELY让我想要的文件繁忙,我需要释放资源,否则webclient或其他任何东西都不能使用该文件:

WebClient webClient = new WebClient(); 
string remote = "sample.jpg"; 
string px = Request.PhysicalApplicationPath.ToString(); 
if (File.Exists(px+"1.jpg") != true) 
{ 
    string local = px + "1.jpg"; 
    webClient.DownloadFile(remote, local); 
} 
else 
{ 
    string local = px + "2.jpg"; 
    webClient.DownloadFile(remote, local); 
} 
try
{
    byte A, R, G, B;
    Color pixelColor;
    Color pixelColor1;

    string rt = px + "1.jpg";
    string rt1 = px + "2.jpg";

    System.Drawing.Image a = System.Drawing.Image.FromFile(rt);
    Bitmap bitmapImage = new Bitmap(a);

    System.Drawing.Image a1 = System.Drawing.Image.FromFile(rt1);
    Bitmap bitmapImage1 = new Bitmap(a1);



    List<string> list = new List<string>();


    for (int y = 0; y < bitmapImage.Height; y++)
    {
        for (int x = 0; x < bitmapImage.Width; x++)
        {
            pixelColor = bitmapImage.GetPixel(x, y);
            pixelColor1 = bitmapImage1.GetPixel(x, y);

我收到此错误。

  

第168行:webClient.DownloadFile(remote,local);“[IOException:进程无法访问文件

2 个答案:

答案 0 :(得分:2)

问题是webclient仍然挂在您的文件上。

尝试部署webclient以释放其资源。

WebClient webClient = new WebClient(); 
string remote = "sample.jpg"; 
string px = Request.PhysicalApplicationPath.ToString(); 
if (File.Exists(px+"1.jpg") != true) 
{ 
    string local = px + "1.jpg"; 
    webClient.DownloadFile(remote, local); 
} 
else 
{ 
    string local = px + "2.jpg"; 
    webClient.DownloadFile(remote, local); 
} 
webClient.Dispose()

答案 1 :(得分:1)

知道它已经很老了,但请尝试使用块。

using (WebClient client = new WebClient())
{
   client.DownloadFile(remotePath, localPath);
}