代码改变世界

C# The process cannot access the file because it is being used by another process

2016-04-05 09:32  Dorisoy  阅读(3060)  评论(0编辑  收藏  举报

C# The process cannot access the file because it is being used by another process

 
The process cannot access the file because it is being used by another process.
This error message is mostly comes up,
when you try to access a file which is opened by another process.

You may open an image file in one of your form in a picturebox with usingImageFromFile or something.
I mostly use memorystream to open an image.
After read it in byte[] write it into a stream and close it.

You can check whether a file is being used or not with a simple function.
Try to open a file with none share.
public bool IsFileUsedbyAnotherProcess(string filename)
 {
 try
 {
  File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None);
}
catch (System.IO.IOException exp)
{
return true;
}
return false;
 
}

This function will return true if
the file because it is being used by another process or not.