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

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

  • Wednesday, July 12, 2006 7:44 AM
     
     

    Hey all

    This is annoying, I want to perform a copy or move or read operation on a file but the file is already open in word or notepad, whatever.

    No when I try for example to rename the file that is open in word the system tells me that I can't do it since word holds it.

    How can I do the same in C#, meaning checking if the file is open and alert which application holds it.

    Itzik

All Replies

  • Wednesday, July 12, 2006 10:49 AM
     
     Answered

    Hi,

    What you can do is trying to aquire an exclusive share on the file, if you success it means that the file is not used by any other process.

    Use the FileShare enumerator when you open the file, therefore your steps should be:

    1) Try to open a file with None sharing

    2) Close the handle (otherwise not even you can move it :-)

    3) If there is no exception you can move the file.

    Hope this helps.

    Regards

  • Wednesday, July 12, 2006 12:05 PM
     
     

    I guess you mean something like that

    public bool CheckIfFileIsBeingUsed(string fileName){

         try{

             File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.None);

          }

          catch (Exception exp){

               return true;

          }

          return false;

    }

     

    OK

    Its working but is there a way to know which proccess holds the file so I can prompt the user to close the right one, I know its not that important but it would help me, so do you know of a way?

    Itzik

  • Wednesday, July 12, 2006 2:11 PM
     
     

    Hi,

    I am not aware of any function to do so, indeed when you try to delete a file in windows that is used by another process it also states that another process is using the file but it does not say to you which one.

    Sorry,

    Salva

  • Thursday, July 13, 2006 11:53 AM
    Moderator
     
     Proposed Answer
    Be careful doing it this way, you'll think the file is locked even when it doesn't exist.  Instead of catching System.Exception, catch System.IO.IOException...

    • Proposed As Answer by SunDisplay Wednesday, June 20, 2012 8:22 PM
    •  
  • Thursday, September 21, 2006 5:55 AM
     
     

    Hey...

    I have the same problem, but I want to open the file for read - event if it's already opened by another process...

    Thanks.

  • Wednesday, October 11, 2006 8:10 AM
     
     
    I'd like to know the answer to this too (open a file for read that is already open by an external process).

    As a workaround I copied the file (File.Copy(.....) ) and opened the copy. Its really annoying since my text editor can open a file that is currently locked by another process, the copy process *may* be reading the bytes when copying, but C# won't let me open for read access the very same file.
  • Saturday, October 14, 2006 6:41 PM
     
     

    I came accros this problem too...

     

    I'm trying to send a file from the Server i worte and I am SURE that no program use this file

    and still i cant open the file in order to send it away,  lets say that a program is using this file (its a BMP)

    even then, Why we can't Open file for READ ONLY even if it is Locked.

    FileOpen(hIn, sFile, OpenMode.Binary, OpenAccess.Read)

    Thanks ahead, Alon.

  • Sunday, October 15, 2006 7:10 PM
    Moderator
     
     Answered
    The Bitmap class has a special problem with file locking.  GDI+ puts a lock on the file after loading it.  Check my code in this thread for a work-around.
  • Sunday, October 15, 2006 7:33 PM
     
     

    Thanks!

    that solved that issue 

     

    Alon.

     

  • Thursday, October 26, 2006 7:57 PM
     
     Proposed Answer

    When I tried your code, it does determine if the file is locked, but in doing so, it locks the file.  I modified your code slightly to fix this.

    Public Function FileIsLocked(ByVal strFullFileName As String) As Boolean
    Dim blnReturn As Boolean =
    False
    Dim fs As
    System.IO.FileStream

    Try
        fs = System.IO.File.Open(strFullFileName, IO.FileMode.OpenOrCreate, IO.FileAccess.Read, IO.FileShare.None)
        fs.Close()
    Catch ex As
    System.IO.IOException
        blnReturn =
    True
    End Try

    Return blnReturn
    End Function

    • Proposed As Answer by osveo Wednesday, December 23, 2009 9:45 AM
    •  
  • Tuesday, April 17, 2007 3:12 PM
     
     

    Thanks for the good idea (copying the file first)

     

    If somebody knows a way to read a file that is already opened exclusively by an another process,

    please tell me.

  • Tuesday, August 21, 2007 1:00 PM
     
     Proposed Answer

    Use FileShare.Read to read a file even if it is opened exclusively by an another process. The default value is FileShare.None, we need to change this.

    • Proposed As Answer by Tazeem Ansari Thursday, April 23, 2009 11:06 AM
    •  
  • Wednesday, September 05, 2007 2:58 AM
     
     Proposed Answer
    Well, to open the file that is already open by other process I had to specify FileShare.ReadWrite. That is with FileShare you specify what other users can do with that file, not what you will do with it.

    According to MSDN,
    "A typical use of this enumeration is to define whether two processes can simultaneously read from the same file. For example, if a file is opened and Read is specified, other users can open the file for reading but not for writing."
    • Proposed As Answer by Tazeem Ansari Thursday, April 23, 2009 11:06 AM
    •  
  • Tuesday, September 11, 2007 5:33 PM
     
     Proposed Answer
    Hi there,

    Have a question. l want to disable system file protection on my xp sp2, so l downloaded the the sfc_os.dll (2600.1106) and created a backup sfc_os.bak opened it with hexeditor and changed the values, everything like is mentioned here in this link http://pubs.logicalexpressions.com/pub0009/LPMArticle.asp?ID=510 but when l had to import the one in the system32 folder using cmd.exe a message appears containing the following  "The process cannot access the file because it is being used by another process. 0 files copied. the command l am attempting to put is "copy sfc_os.bak sfc_os.dll /y" but it does not work for me. Anyway it worked well in the dllcache folder. Please anyone who can help? l need to disable WFP because l need to replace some essential files for my new graphic editor. Thanks help much appreciated !!
    • Proposed As Answer by Tazeem Ansari Thursday, April 23, 2009 11:05 AM
    •  
  • Thursday, April 23, 2009 11:12 AM
     
     Proposed Answer

    I think what all the you people is suggesting is wrong ...

    A file is unmanaged resource which wont release until we release that explicitly.

    always use "using" when you use a file with clearing the file .

    using clear the resourse and close also and than reopen on your request you will not face this problem again.

     

     

    using (fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))

    {

    fs.SetLength(0);

    config.Save(fs);

    fs.Flush();

    }

    thanks

    Tazeem Ansari

    • Proposed As Answer by Tazeem Ansari Thursday, April 23, 2009 11:27 AM
    •  
  • Thursday, June 11, 2009 6:42 PM
     
     
    I agree with Tazeem the solution worked for me.
    mohanr
  • Friday, August 28, 2009 12:51 AM
     
     Proposed Answer
    What if the file was opened from another process? and is still open?

    • Proposed As Answer by Tazeem Ansari Tuesday, September 01, 2009 7:46 AM
    •  
  • Tuesday, September 01, 2009 7:48 AM
     
     Proposed Answer
    Then before using the file close the file as a standard practice. If system not allows the file to close then open it in sharing mode i think it will help you. to close a file use file.close() method. and to open in share mode user


    fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)

    you can change the FileShare mode to Read/ReadWrite/Node ,similer for FileAccess use the access mode as per your requirement. 


    Tazeem Ansari
    • Proposed As Answer by Tazeem Ansari Tuesday, September 01, 2009 7:53 AM
    •  
  • Tuesday, October 20, 2009 5:00 AM
     
     Proposed Answer
      bool _FileUse = false;
                                while (!_FileUse)
                                {
                                    try
                                    {
                                        StreamWriter strWriter = new StreamWriter(p_directoryPath + p_Filename + ".txt", true);
                                        strWriter.Write(_Builder);
                                        strWriter.AutoFlush = true;
                                        strWriter.Flush();
                                        strWriter.Dispose();
                                        strWriter.Close();
                                        Thread.Sleep(1000);
                                        _FileUse = true;
                                    }
                                    catch (Exception ex)
                                    {
                                        Thread.Sleep(1000);
                                        _FileUse = false;
                                    }

    try this , simple and its is like fake sign to threads, while file is using by particular threads check for its availability. this idea will works for hundreds of request to a sing file and it will log each and every stream to file :).

    Thanks & Regards
    Abdul Aziz Farooqi
  • Wednesday, January 13, 2010 3:36 PM
     
     Proposed Answer
    Well this works for me....

                        bool _Open = true;
                        while (_Open)
                        {
                            try
                            {
                                FileStream fs = System.IO.File.Open(base.Server.MapPath("path"), System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None);
                                fs.Close();
                                fs.Dispose();
                                break;
                            }
                            catch
                            {
                                System.Drawing.Image fullSizeImg = System.Drawing.Image.FromFile(base.Server.MapPath("path"));
                                fullSizeImg.Dispose();                           
                            }
                        }
                   
    • Proposed As Answer by march111 Tuesday, January 15, 2013 5:54 PM
    •  
  • Tuesday, April 20, 2010 5:51 PM
     
     

    In C#, if 2 processes are reading and writing to the same pdf file, what is the best way to avoid process locking exceptions? - I am using itextsharp

    The below is the code

      using (Stream inputPdfStream = new FileStream(@"C:\AERShare\Variables.pdf", FileMode.Open, FileAccess.Read, FileShare.Read))
            using (Stream inputImageStream = new FileStream(@"C:\AERShare\"+strName+".jpg", FileMode.Open, FileAccess.Read, FileShare.Read))
            using (Stream outputPdfStream = new FileStream(@"C:\AERShare\result.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
            {
                var reader = new PdfReader(inputPdfStream);
                var stamper = new PdfStamper(reader, outputPdfStream);
                var pdfContentByte = stamper.GetOverContent(1);

                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);
                image.SetAbsolutePosition(100, 100);           
                pdfContentByte.AddImage(image);
                stamper.Close();
            }

    The above code is working fine but it creates new pdf file . But i want write to same existing pdf file

    It through's a below exception

    system.io.ioexception the process cannot access because it is being used by othe file .

    Can anyone guide me ?

    Thanks,

    Steed.

  • Wednesday, June 23, 2010 7:48 AM
     
     

    I use code in this thread for a work-around and it is good, thanks

    Yes But the real question remained unanswered How to know the process (Name, ID, thread, which has locked the damn file
    nothing
  • Friday, October 01, 2010 12:18 PM
     
     
    @Abdul, nice tip its work for me.
  • Tuesday, May 10, 2011 4:20 PM
     
     

    I had the same problem and was getting the error  "The process cannot access the file 'c:\xyz\pqr.pdf' because it is being used by another process".

    I tried to close and dispose the filestream where it was opened previously. But that did not change anything.

    After going through the program I observed that I was adding the file to mailmessage objects attachments collection to send it as an attachment to the email using the SMTPClient object.

    I was using the following statement to attach the file

    Dim

    msg As New MailMessage()

    Dim

     

    attach As New System.Net.Mail.Attachment(s)

    msg.Attachments.Add(attach)

    I added a msg.Dispose at the end of the method after sending the email and this solved the problem. Hopes this will help anyone having similar problem.

     

     

  • Thursday, May 26, 2011 9:53 PM
     
      Has Code

    Hi, i have the same problem when i try to use File.WriteAllText() into a file after do another methods, having received an error message:

    No se controló System.IO.IOException
     Message=El proceso no puede obtener acceso al archivo 'C:\temp\temp.html' porque está siendo utilizado en otro proceso.
     Source=mscorlib
     StackTrace:
     en System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
     en System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
     en System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
     en System.IO.StreamWriter.CreateFile(String path, Boolean append)
     en System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding, Int32 bufferSize)
     en System.IO.StreamWriter..ctor(String path, Boolean append, Encoding encoding)
     en System.IO.File.InternalWriteAllText(String path, String contents, Encoding encoding)
     en System.IO.File.WriteAllText(String path, String contents)
     en Naharro.Desktop.Form1.openedfile(String file) en C:\Users\Ángel Manuel\Programación\Visual Studio 2010\Projects\Naharro\Naharro.Desktop\Form1.cs:línea 79
     en Naharro.Desktop.Form1..ctor() en C:\Users\Ángel Manuel\Programación\Visual Studio 2010\Projects\Naharro\Naharro.Desktop\Form1.cs:línea 41
     en Naharro.Desktop.Program.Main() en C:\Users\Ángel Manuel\Programación\Visual Studio 2010\Projects\Naharro\Naharro.Desktop\Program.cs:línea 20
     InnerException: 
    

    Do you have any answer??


    Ángel Manuel

    Blog Twitter

  • Sunday, June 05, 2011 10:45 AM
     
     
    share your code
    http://www.abdulazizfarooqi.wordpress.com BizTalk Developer UBL Transformation
  • Sunday, June 05, 2011 10:51 AM
     
     Proposed Answer
    share your code
    http://www.abdulazizfarooqi.wordpress.com BizTalk Developer UBL Transformation

    I could fix that. Look http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/f8c6d5ee-e65e-4ed7-8c62-f2e33d6fc7df/#144ab6f7-030b-469a-84e1-a499b18afa91.

    Regards


    Ángel Manuel

    Blog Twitter

  • Tuesday, August 09, 2011 9:50 AM
     
      Has Code
    string imagePath = @"c:\some_image_file.png";
    Image tempImage = Image.FromFile(imagePath);
    Image realImage = new Bitmap(tempImage);
    tempImage.Dispose();
    


    Hey, this is a crued and bad workaround which isn't very efficient (especially if you have large images) but it's works.

    //MarX

  • Wednesday, August 10, 2011 1:44 PM
     
     

    Use SysInternals Process Explorer.  Click Find>File Handle or DLL, type in the filename and click Search.

  • Sunday, September 04, 2011 9:41 AM
     
     

    I think this is the bug of system.drawing object.

    Compressed images like jpg, png not work.

    I used bmp file format. Now it is work at web and form applications too.

    "

        Dim xx As New System.Drawing.Bitmap(536, 544)

        tmpGr = Graphics.FromImage(xx)

      Dim myFnt As New Font("Arial", 8)

      Dim brs As New SolidBrush(Color.Black)

      tmpGr.DrawString("test string", myFnt, brs, 446, 337)

     Dim tmpfl As String = Server.MapPath("test.jpg")

    Using m = New MemoryStream()

                    xx.Save(m, System.Drawing.Imaging.ImageFormat.Bmp)
                    Dim img = Image.FromStream(m)
                    img.Save(tmpfl, System.Drawing.Imaging.ImageFormat.Jpeg)

    End Using

                xx.Dispose()
                xx = Nothing