如何释放BitMap类保存的文件

时间:2012-08-29 08:45:54

标签: c#

我有以下代码:

Bitmap image = new Bitmap(filePath);
...
image.Save(someOtherPath);
image.Dispose();
File.Delete(filePath);
File.Move(someOtherPath, filePath);

File.Delete行引发以下错误:

The process cannot access the file '...' because it is being used by another process.

如何让C#释放它对文件的锁定?

2 个答案:

答案 0 :(得分:2)

尝试

using(var image = new Bitmap(filepath))
{
    image.Save(someOtherPath);
}


File.Delete(filePath);
File.Move(someOtherPath, filePath);

答案 1 :(得分:0)

the mistake came from the file open by your Image class
Image image;

using(FileStream myStream = new FileStream(path))
  {    
     image = Image.FromStream(myStream);
  }