File is being used by another process

| August 10, 2010 | 0 Comments


A small problem that can be solved by just little sense of intelligence proves  that leaving a little loop hole in your program can make your peace of mind to disturb. Actually I was developing a small application named Screenshot. The application was meant for capturing screen shot of active display device.

As application saves screen shot at specified location I was trying to display same screenshot in application to user, that would pop up (because earlier it was hidden so that it should not hinder screenshoting). But when I try the same task second times, my application return a lovely error,  The process  cannot access  the file xyz because file is being used by another  process.


So now I started research for solution or you can say search for it online and by MSDN. But MSDN proves of no use here. Again online world was helpful for the same but not fully because there are several ways to avoid that problem. Here are few as I remember:

    1. One should use the code that is creating this type of error code in statement using. One interesting thing that I came to know about using was that it is somewhat equivalent to try…finally block. And then we should explicitly close the instance of object so that resource can be unallocated from memory by GC (Garbage Collector) by calling Dispose(). See below:
// By using keyword
using (FileStream fs=new FileStream("C:\\Save.txt",FileMode.Open, FileAccess.Read, FileShare.Read))
                    //Do something here

// By try...finally block
 FileStream fs;
                    fs = new FileStream("C:\\Save.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
  1. Try to check whether particular file is been locked by some process. And if it is locked wait for some seconds & then retry. Or you can use ProcessExplorer , a little tool to check which process is accessing that file.

Finally I get a suggestion from website  to make that particular object remove from memory by Dispose() method. For e.g., in my case I was holding address of that file in Bitmap instance. So I solved by:-

// Bitmap bmp declared at class level
// and object created where we are accessing that file
if (bmp != null)
               //Releasing all resources of bmp

               // Method used to avoid delay in Disposing

And finally the daunting problem gets easy solution.

Category: .NET, Error and Solution

Leave a Reply

%d bloggers like this: