Skip to content

Waiting for a locked file

Juan Antonio 0

Asked Jan 19, 2006, 7:15 AM EST5 answers
Share
LinkedInX
Hello!

   I have one program that modifies one file. After this program finalizes is started a .bat file for renaming the file that has been modified by the program. Some times I get the message "The process cannot access the file because it is being used by used by another program" The program that has modified the file has not free the file yet. I want to make another program in C# for waiting until the file be free but I didn't find any function within System.IO for doing this task. Is there any way to test this condition into C#?


Best regards

5 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • 0

    Did You remember to close the file stream that modified the file? All streams have a Close method, that frees the system resources associaced by the stream.

    C#
    
    TextWriter file = null;
    
    try
    
    {
    
       file = new StreamWriter("filename.txt");
    
       //write here
    
       file.WriteLine("Contents of the file");
    
    }
    
    catch(Exception ex)
    
    {
    
       //handle exceptions here
    
    }
    
    finally
    
    {
    
       //close file here, not in try block!!
    
       file.Close();
    
    }
    0
  • 0
    I have no access to the source code of the program which is modifying the file. So I need to make a program to check when the file is free.

    Best regards
    0
  • 0
    Is the program that is using the file an exe or a com component or what? Anyway, you have a couple of immediate options: 1.) The Cheesy Low Profile method - After the other component is done (if you KNOW it is done...) use Thread.Sleep(xxx) in your code for a few hundred msecs to give the other program a little time to unload. 2.) The Almost Like Science method - When the other program starts, use the API to find it's process handle. Use the WaitForSingleProcess api call (you can loop or wait with a timeout value) until the process is done and then continue on your way.
    0
  • 0
    OOPS forgot to mention... there's always the try-catch block in nested loop method... as soon as you can open the file your try block will succeed, otherwise catch and loop again.
    0
  • 0
    The program which is modifying the file is a java program. We made tests about sleeping before the .bat is executed and we need to wait about 5 seconds for always working. These 5 seconds are very much seconds because the .bat is executed a lot of times. I'd like to get one solution without getting into account the first process, only the locked filen and the .bat. Anyone knows any property indicating a file is locked by another process?

    Best regards

    (Sorry my english)
    0