Is there a way to check if a file is in use?

641,334

Solution 1

Updated NOTE on this solution: Checking with FileAccess.ReadWrite will fail for Read-Only files so the solution has been modified to check with FileAccess.Read.

ORIGINAL: I've used this code for the past several years, and I haven't had any issues with it.

Understand your hesitation about using exceptions, but you can't avoid them all of the time:

protected virtual bool IsFileLocked(FileInfo file)
{
    try
    {
        using(FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None))
        {
            stream.Close();
        }
    }
    catch (IOException)
    {
        //the file is unavailable because it is:
        //still being written to
        //or being processed by another thread
        //or does not exist (has already been processed)
        return true;
    }

    //file is not locked
    return false;
}

Solution 2

You can suffer from a thread race condition on this which there are documented examples of this being used as a security vulnerability. If you check that the file is available, but then try and use it you could throw at that point, which a malicious user could use to force and exploit in your code.

Your best bet is a try catch / finally which tries to get the file handle.

try
{
   using (Stream stream = new FileStream("MyFilename.txt", FileMode.Open))
   {
        // File/Stream manipulating code here
   }
} catch {
  //check here why it failed and ask user to retry if the file is in use.
}

Solution 3

Use this to check if a file is locked:

using System.IO;
using System.Runtime.InteropServices;
internal static class Helper
{
const int ERROR_SHARING_VIOLATION = 32;
const int ERROR_LOCK_VIOLATION = 33;

private static bool IsFileLocked(Exception exception)
{
    int errorCode = Marshal.GetHRForException(exception) & ((1 << 16) - 1);
    return errorCode == ERROR_SHARING_VIOLATION || errorCode == ERROR_LOCK_VIOLATION;
}

internal static bool CanReadFile(string filePath)
{
    //Try-Catch so we dont crash the program and can check the exception
    try {
        //The "using" is important because FileStream implements IDisposable and
        //"using" will avoid a heap exhaustion situation when too many handles  
        //are left undisposed.
        using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) {
            if (fileStream != null) fileStream.Close();  //This line is me being overly cautious, fileStream will never be null unless an exception occurs... and I know the "using" does it but its helpful to be explicit - especially when we encounter errors - at least for me anyway!
        }
    }
    catch (IOException ex) {
        //THE FUNKY MAGIC - TO SEE IF THIS FILE REALLY IS LOCKED!!!
        if (IsFileLocked(ex)) {
            // do something, eg File.Copy or present the user with a MsgBox - I do not recommend Killing the process that is locking the file
            return false;
        }
    }
    finally
    { }
    return true;
}
}

For performance reasons I recommend you read the file content in the same operation. Here are some examples:

public static byte[] ReadFileBytes(string filePath)
{
    byte[] buffer = null;
    try
    {
        using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
        {
            int length = (int)fileStream.Length;  // get file length
            buffer = new byte[length];            // create buffer
            int count;                            // actual number of bytes read
            int sum = 0;                          // total number of bytes read

            // read until Read method returns 0 (end of the stream has been reached)
            while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
                sum += count;  // sum is a buffer offset for next reading

            fileStream.Close(); //This is not needed, just me being paranoid and explicitly releasing resources ASAP
        }
    }
    catch (IOException ex)
    {
        //THE FUNKY MAGIC - TO SEE IF THIS FILE REALLY IS LOCKED!!!
        if (IsFileLocked(ex))
        {
            // do something? 
        }
    }
    catch (Exception ex)
    {
    }
    finally
    {
    }
    return buffer;
}

public static string ReadFileTextWithEncoding(string filePath)
{
    string fileContents = string.Empty;
    byte[] buffer;
    try
    {
        using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
        {
            int length = (int)fileStream.Length;  // get file length
            buffer = new byte[length];            // create buffer
            int count;                            // actual number of bytes read
            int sum = 0;                          // total number of bytes read

            // read until Read method returns 0 (end of the stream has been reached)
            while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
            {
                sum += count;  // sum is a buffer offset for next reading
            }

            fileStream.Close(); //Again - this is not needed, just me being paranoid and explicitly releasing resources ASAP

            //Depending on the encoding you wish to use - I'll leave that up to you
            fileContents = System.Text.Encoding.Default.GetString(buffer);
        }
    }
    catch (IOException ex)
    {
        //THE FUNKY MAGIC - TO SEE IF THIS FILE REALLY IS LOCKED!!!
        if (IsFileLocked(ex))
        {
            // do something? 
        }
    }
    catch (Exception ex)
    {
    }
    finally
    { }     
    return fileContents;
}

public static string ReadFileTextNoEncoding(string filePath)
{
    string fileContents = string.Empty;
    byte[] buffer;
    try
    {
        using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
        {
            int length = (int)fileStream.Length;  // get file length
            buffer = new byte[length];            // create buffer
            int count;                            // actual number of bytes read
            int sum = 0;                          // total number of bytes read

            // read until Read method returns 0 (end of the stream has been reached)
            while ((count = fileStream.Read(buffer, sum, length - sum)) > 0) 
            {
                sum += count;  // sum is a buffer offset for next reading
            }

            fileStream.Close(); //Again - this is not needed, just me being paranoid and explicitly releasing resources ASAP

            char[] chars = new char[buffer.Length / sizeof(char) + 1];
            System.Buffer.BlockCopy(buffer, 0, chars, 0, buffer.Length);
            fileContents = new string(chars);
        }
    }
    catch (IOException ex)
    {
        //THE FUNKY MAGIC - TO SEE IF THIS FILE REALLY IS LOCKED!!!
        if (IsFileLocked(ex))
        {
            // do something? 
        }
    }
    catch (Exception ex)
    {
    }
    finally
    {
    }

    return fileContents;
}

Try it out yourself:

byte[] output1 = Helper.ReadFileBytes(@"c:\temp\test.txt");
string output2 = Helper.ReadFileTextWithEncoding(@"c:\temp\test.txt");
string output3 = Helper.ReadFileTextNoEncoding(@"c:\temp\test.txt");

Solution 4

Just use the exception as intended. Accept that the file is in use and try again, repeatedly until your action is completed. This is also the most efficient because you do not waste any cycles checking the state before acting.

Use the function below, for example

TimeoutFileAction(() => { System.IO.File.etc...; return null; } );

Reusable method that times out after 2 seconds

private T TimeoutFileAction<T>(Func<T> func)
{
    var started = DateTime.UtcNow;
    while ((DateTime.UtcNow - started).TotalMilliseconds < 2000)
    {
        try
        {
            return func();                    
        }
        catch (System.IO.IOException exception)
        {
            //ignore, or log somewhere if you want to
        }
    }
    return default(T);
}

Solution 5

Perhaps you could use a FileSystemWatcher and watch for the Changed event.

I haven't used this myself, but it might be worth a shot. If the filesystemwatcher turns out to be a bit heavy for this case, I would go for the try/catch/sleep loop.

Share:
641,334
Dawsy
Author by

Dawsy

Updated on June 09, 2021

Comments

  • Dawsy
    Dawsy almost 3 years

    I'm writing a program in C# that needs to repeatedly access 1 image file. Most of the time it works, but if my computer's running fast, it will try to access the file before it's been saved back to the filesystem and throw an error:

    "File in use by another process"

    I would like to find a way around this, but all my Googling has only yielded creating checks by using exception handling. This is against my religion, so I was wondering if anyone has a better way of doing it?

    • BobbyShaftoe
      BobbyShaftoe almost 15 years
      All right, you can test it by examining all the open handles on the system. However, since Windows is a multitasking operating system, there is a chance that right after you run the code to determine if the file is open and you deem it is not, a process code start using that file, then by the time you try to use it, you receive an error. But, there is nothing wrong with checking first; just don't assume it is not in use when you actually need it.
    • BobbyShaftoe
      BobbyShaftoe almost 15 years
      But just for this specific issue; I'd recommend not examining the file handles and just try some preset number of times, say 3-5 before failing.
    • Catchwa
      Catchwa almost 15 years
      How is this image file generated? Can you stop/sleep/pause your program until the generation is completed? That is by far a superior way to handle the situation. If not, then I don't think you can avoid using exception handling.
    • jwg
      jwg over 11 years
      Isn't all use of exceptions a check on some assumption by doing something potentially dangerous while deliberately not ruling out the possibility of failure?
    • Lee Louviere
      Lee Louviere about 11 years
      Your philosophy has a bad understanding of exceptions. Most people think exceptions means holy-crap-out-of-doom-something's-wrong-die-die-die. When exception means.... exception. It means something exceptional occurred that you need to "handle" (or account for). Maybe you want to keep retrying for data access, maybe the user needs to know that you can't get a connection. What do you do? You handle the ConnectionFailedException and notify the user, so maybe, they'll stop trying after an hour, and notice the cable is unplugged.
    • Leif Neland
      Leif Neland almost 7 years
      Why have the checking and processing in different procedures? try {open file in FileShare.None; process file; close file} catch {filelocked) {//locked, we'll get it next time}
    • webs
      webs over 5 years
      Lee Louviere the op has a valid dislike for working with exceptions. If you can easily use filexists method to know if a file exists what similar command exists to know if the file you want to work with is in use? In fact i believe that is the question the op is really asking.
    • Justine Krejcha
      Justine Krejcha almost 4 years
      @webs Some exceptions are just a fact of life. Using File.Exists() is good, but like the answer says, it's not always possible to avoid them. For example, a file could exist between the time you check if it exists and when you actually open it. That indefinite period is good enough most of the time, but there are no guarantees and so an exception handler should wrap the call to open it, etc.
    • Andrew Henle
      Andrew Henle almost 4 years
      @webs If you can easily use filexists method to know if a file exists what similar command exists to know if the file you want to work with is in use? A bit late here, but both of those examples are TOCTOU bugs. The results are immediately invalid. "Check-then-do" is useless - the "check" can not be identical to the "do", so the "check" can fail for different reasons or succeed when the "do" would fail. When you need to open a file OPEN THE FILE. Nothing else can give you definitive proof that opening will work.
    • ChrisMercator
      ChrisMercator over 3 years
      What if I do not want to figure out if I CAN write to a file at all, but if i should rather not although i could, because someone else is currently working on that same file?
  • adeel825
    adeel825 over 14 years
    This is a great solution, but I have one comment - you may wan't to open the File with access mode FileAccess.Read since ReadWrite will always fail if the file happens to be read-only.
  • Tim Lloyd
    Tim Lloyd almost 14 years
    Good answer, but a problem is that the file may not actually exist which will cause a FileNotFound exception - this is an IOException. The IOException catch block will catch this and the method result interprets this as file locked, when in fact the file does not actually exist - this could lead to hard to diagnose bugs. Tricky one from an API perspective - perhaps the API should be GetFileState which returns an enum: Locked, NotFound, KnockYourselfOut. :) Of course an UnauthorizedAccessException could be raised, which is not an IOException...
  • Polyfun
    Polyfun almost 14 years
    -1. This is a poor answer, because the file could become locked by another thread/process after it is closed in IsFileLocked, and before your thread gets a chance to open it.
  • Sedat Kapanoglu
    Sedat Kapanoglu over 13 years
    +1. There is no 100% safe way to "learn if a file is in use" because milliseconds after you do the check, the file may not be in use anymore, or vice versa. Instead, you just open the file and use it if there are no exceptions.
  • Clément
    Clément about 13 years
    Albeit it works in this case, this answer doesn't apply to other situations. For example, if you want to copy a file, this code may raise an exception, whereas System.Copy wouldn't have complained. Ideas on how to circumvent this problem?
  • ChrisW
    ChrisW about 13 years
    CFP, even though you can copy an open file with System.Copy, it's up to you to determine whether the locked file would contain valid data or not. If yes, then you probably don't have to check.The safest approach would be to check whether the file is open/locked, then proceed with File.Copy().
  • Admin
    Admin almost 13 years
    Using a FileSystemWatcher does not help, because the Created and Changed events raise at the beginning of a file creation/change. Even small files need more time to be written and closed by the operating system than the .NET application needs to run through the FileSystemEventHandler Callback. This is so sad, but there is no other option than to estimate the wait time before accessing the file or run into exception loops...
  • TamusJRoyce
    TamusJRoyce almost 13 years
    Too bad .NET doesn't support CAS. Something like, TryOpenFile(Ref FileHandle) that returns success/failure. There should always be a work-around not rely on exception handling alone. I wonder how Microsoft Office does it.
  • Spence
    Spence almost 13 years
    The key thing to understand here is that this API is simply using the windows API to get a file handle. As such they need to translate the error code received from the C API and wrap it to an exception to throw. We have exception handling in .Net so why not use it. That way you can write a clean forward path in your code and leave the error handling in a separate code path.
  • Matthew
    Matthew over 12 years
    Possibly dumb question, but if you return true in the catch, won't the finally block not get called? Is that a problem?
  • Ignacio Soler Garcia
    Ignacio Soler Garcia over 12 years
    Matthew, the finally is always called, whatever happens. Always. Dot. :)
  • Louis Rhys
    Louis Rhys over 12 years
    @adeel825 will changing it to read cause any side-effect? For example, being unable to detect files that are only write-locked?
  • Wiebe Tijsma
    Wiebe Tijsma about 12 years
    @SoMoS actually, the finally block is NOT always executed, there's some exceptions that stop your flow (think ThreadAbortException, StackOverflowException, OutOfMemoryException)
  • Ignacio Soler Garcia
    Ignacio Soler Garcia about 12 years
    @Zidad: if these exceptions happens outside the finally block then the finally will get executed. If they happens inside the finally the flow breaks but anyway you were already executing the finally so the finally always is executed (but maybe it does not end the execution).
  • Wiebe Tijsma
    Wiebe Tijsma about 12 years
    @SoMoS No that's not entirely correct, but you were right about the ThreadAbortException, I didn't know that, but see this SO question about the other exceptions: stackoverflow.com/questions/107735/…
  • Ben F
    Ben F almost 12 years
    FileSystemWatcher doesn't handle lots of changes at the same time very well though, so be careful with that.
  • itsho
    itsho almost 12 years
    small note: you might consider use using block for automatic disposing, or at least, dispose the stream by yourself.
  • Manuzor
    Manuzor almost 12 years
    I think this is a great answer. I'm using this as an extension method á la public static bool IsLocked(this FileInfo file) {/*...*/}.
  • Ben Hughes
    Ben Hughes over 11 years
    People who put usings in try/catch blocks confuse me. Just use a try/catch/finally....
  • Spence
    Spence over 11 years
    The using statement is to ensure the stream is closed after I'm done. I think you'll find that the using() {} is less characters than try {} finally { obj.Dispose() }. You'll also find that you now need to declare your object reference outside the using statement, which is more typing. If you have a explicit interface you'd also have to cast. Finally you want to dispose ASAP, and the finally logic may have UI or any other long running actions that have little to do with calling IDispose. </rant>
  • jwg
    jwg over 11 years
    The last point is a little artificial. Either you do have UI calls in your finally clause, in which case you do, or you don't, in which case you don't.
  • Spence
    Spence over 11 years
    that doesn't negate the fact that you have to declare your object outside the try and have to explicitly call dispose, which using does for you and means the same thing.
  • Pierre Lebeaupin
    Pierre Lebeaupin about 11 years
    @ChrisW: you might be wondering what is going on. Do not be alarmed. You're just being subject to the wrath of the Daily WTF community: thedailywtf.com/Comments/…
  • Drew Delano
    Drew Delano about 11 years
    @PierreLebeaupin: And why wouldn't that be alarming?
  • Lee Louviere
    Lee Louviere about 11 years
    @ChrisW Why is that a bad thing. This community is here to point out good and bad answers. If a bunch of professionals notice this is a bad thing, and join to downvote, then the site is WAI. And before you get negative, if you read that article, they say to "upvote the right answer" not downvote the wrong one. Do you want them to explain their upvotes in comments as well. Thanks for introducing me to another good site!
  • Kris
    Kris about 11 years
    I would upvote if there weren't so many "magic numbers" in there en.wikipedia.org/wiki/Magic_number_(programming)
  • Harry Johnston
    Harry Johnston about 11 years
    Doesn't this have the same problem as the other answer, i.e., it throws the handle away instead of saving it for whatever the programmer actually wanted to do with the file?
  • DiskJunky
    DiskJunky about 11 years
    anything using this method is itself suseptable to race conditions. E.g., If I call this function and then proceed to try and write to the file it'll fail. Any writes to a file should be handled directly and not call "check if a file is X" logic immediately beforehand. The function itself is "correct" but it's usage by the unwary/inexperienced will leave to subtle errors
  • Bob
    Bob about 11 years
    @HarryJohnston // File/Stream manipulating code here - you're supposed to use the file (read/write/etc.) within the try block, thereby avoiding the race condition where another process can lock the file between the check and open - because the check and open is one atomic operation here.
  • Harry Johnston
    Harry Johnston about 11 years
    @Bob: that comment wasn't part of the answer until yesterday. :-) It makes it a lot clearer.
  • Kris
    Kris about 11 years
    I was referring to the errorCode comparisons, not the bit shifts. though now you mention it...
  • Lakey
    Lakey about 11 years
    The actual check you perform is fine; putting it inside a function is misleading. You do NOT want to use a function like this prior to opening a file. Inside the function, the file is opened, checked, and closed. Then the programmer ASSUMES the file is STILL ok to use and tries opening it for use. This is bad because it could be used and locked by another process that was queued up to open this file. Between the 1st time it was opened (for checking) and the 2nd time it was opened (for use), the OS could have descheduled your process and could be running another process.
  • Mathieu Le Tiec
    Mathieu Le Tiec about 11 years
    BTW, have you guys noticed while debugging and watching threads that MS calls their own FSW "FileSystemWather"? What's a wather anyway?
  • Askolein
    Askolein about 11 years
    Your Catch should be on IOException, instead of on general Exception and then a test on type.
  • Askolein
    Askolein almost 11 years
    @JeremyThompson sadly you put the specific IOException after the general one. The general one will catch everything passing by and the specific IOException will always be lonely. Just swap the two.
  • Kiquenet
    Kiquenet almost 11 years
    what is IsFileBeingUsed ? source code about IsFileBeingUsed ?
  • shindigo
    shindigo about 10 years
    I like this solution. One other suggestion: inside the catch as an else to the if(IsFileLocked(ex)) I would throw ex. This will then handle the case where the file does not exist (or any other IOException) by throwing the exception.
  • Jeremy
    Jeremy about 10 years
  • Jeremy
    Jeremy about 10 years
    Catching IOException does not necessarily indicate a locked file, because I believe you'll catch all exceptions inheriting from IOException which include DirectoryNotFoundException, DriveNotFoundException, EndOfStreamException, FileLoadException, FileNotFoundException, etc. msdn.microsoft.com/en-us/library/vstudio/…
  • Cullub
    Cullub over 9 years
    @jcolebrand locks what? the one you copied? Or the one you put in the temp dir?
  • jcolebrand
    jcolebrand over 9 years
    if you copy the file, expecting nobody else to be working on it, and you're going to use the temp file, and then someone locks it right after you copy it, then you've potentially lost data.
  • Suamere
    Suamere over 9 years
    @BenHughes Don't be confused, do some research. One of .NET's biggest strengths is garbage collection for managed resources. using blocks should be used 99.9% of the time for anything implementing IDisposable. As you appear to possibly know: using blocks pretty much just IL down to a try/finally with a x.Dispose() call. But that doesn't include catching or handling exceptions. So the one or so lines of code that might actually need handling (the FileStream with File.Open in this case) should be wrapped to catch. Breaking the using into a custom try/catch/finally adds smell.
  • jheriko
    jheriko over 9 years
    "Understand your hesitation about using exceptions, but you can't avoid them all of the time" er really? my entire career seems to have not required me to ever use them... only endure them out of politeness.
  • Nick
    Nick over 9 years
    What if you don't have write access to the folder that the file is in?
  • Jeremy Thompson
    Jeremy Thompson over 9 years
    Hi, Since the order of answers changes can you clarify which post above you mean for readers of this popular QA. Thanks.
  • atlaste
    atlaste over 9 years
    @JeremyThompson You're right, thanks, I'll edit the post. I'd use the solution from you, mainly because of your correct use of FileShare and checking for a lock.
  • Paul Taylor
    Paul Taylor over 8 years
    The stream object doesn't get Disposed in this solution. Better to wrap it in a using statement.
  • Frédéric
    Frédéric over 8 years
    This solution is more robust than currently accepted one but looks less versatile to me: in some cases, the file manipulating code is a black box working from file name, maybe even in a separated process, and this solution looks unusable in such case.
  • Frédéric
    Frédéric over 8 years
    This solution is less robust than Spence's one but looks more versatile: in some use cases, your file manipulating code is a black box working from file name, maybe even in a separated process, and Spence's solution looks unusable in such case.
  • Frédéric
    Frédéric over 8 years
    @PaulTaylor, close and dispose do the same on stream objects, and it is documented. This code does dispose the stream. using block with nothing to do on the stream would lead to some strange code in this case. Though I tend to always use using on IDisposable, I think this case is way more readable without a using.
  • rboy
    rboy over 8 years
    I've added a more comprehensive way to check for file locks and documented the limitations below: stackoverflow.com/a/33150038
  • Harry Johnston
    Harry Johnston over 8 years
    @Frederic: in that scenario, we shouldn't need to do anything. The black box is responsible for dealing with the possibility that the file is in use, not the caller. (It's true that if you're stuck dealing with an incompetently written black box, you might need a best effort workaround, but that would be a different question.)
  • Harry Johnston
    Harry Johnston over 8 years
    Still has the same problem as the accepted answer - it only tells you whether the file was locked by another process at one particular moment in time, which is not useful information. By the time the function has returned the result may already be out of date!
  • Frédéric
    Frédéric over 8 years
    @HarryJohnston Incompetently written black box? Not the point. Try opening with Ms Excel a xls file still being written to. Should we say it has been incompetently written for that reason? No, we just wait as best as we can for the file to be no more in use, rather than inflicting to the user a "file locked error => please try again". Both solutions here are useful, depending on the real case. My comment was meant to counter statements such as 'This is a poor answer' about ChrisW answer.
  • Harry Johnston
    Harry Johnston over 8 years
    @Frederic: it is a poor answer to this particular question. It might be a good answer to a question about launching Excel.
  • rboy
    rboy over 8 years
    that's true, one can only check at any given moment of time (or subscribe to events), the advantage of this approach over the accepted solution is that it can check for a read only attribute and a write lock and not return a false positive.
  • Spence
    Spence over 8 years
    Sorry just to be clear, you would rather risk a security violation with something that "almost" works, as opposed to something that works reliably and correctly in every case? You aren't required to bother the user, but what exactly are you meant to do if your app can't access the file it needs? Or worse, believe the file is available and then incorrectly progresses forward without access to a file?
  • BloodyRain2k
    BloodyRain2k almost 8 years
    While Polyfun has a point with the possibility of the file becoming locked in the small moment when IsFileLocked returns true and the program actually reopening the file. But that can easily be circumvented by just returning the already opened stream handle instead and a null in case it's locked. Functionally the same as you can simply null check before using it but it keeps the file open since checking.
  • Mr Anderson
    Mr Anderson almost 8 years
    Why is this method virtual, not static?
  • Jeremy Thompson
    Jeremy Thompson over 7 years
    If you want to open the file while another process has it open, specify FileAccess fileAccess = FileAccess.Read, FileShare fileShare = FileShare.ReadWrite
  • BartoszKP
    BartoszKP about 7 years
    What's the purpose of the bit-masking, when in the next line you compare explicitly with a constant? Also, GetHRForException has side effects - starting with .NET 4.5 the HResult property is public.
  • akousmata
    akousmata almost 7 years
    -1 this is a straight up incorrect answer. This only checks if this file is in use "right now" meaning that immediately after you call it, it may immediately be in use by another process and you'll still get the exception. @BloodyRain2k, you are correct, but that isn't pointed out in the answer which still makes it an incorrect answer.
  • CAD bloke
    CAD bloke almost 7 years
    How many seconds until a stack overflow from the recursion in GetStreamAsync()?
  • Ivan Branets
    Ivan Branets almost 7 years
    @CADbloke, you have raised a very good point. Indeed my sample might have stack overflow exception, in case if a file is not available for a long time. Related to this answer stackoverflow.com/questions/4513438/…, it might raise the exception in 5 hours.
  • Ivan Branets
    Ivan Branets almost 7 years
    Related to your use cases it is preferable to throw I/O exception if let's say 10 attempts to read the file have been failed. The other strategy might be increasing waiting time for a second once 10 attempts have been failed. You can also use a mix of both.
  • CAD bloke
    CAD bloke almost 7 years
    I would (and do) simply alert the user the file is locked. They generally locked it themselves so they will probably do something about it. Or not.
  • Ivan Branets
    Ivan Branets almost 7 years
    In some cases, you need to use retry policy since a file might not be ready yet. Imagine a desktop application to download images in some temporary folder. The application starts downloading and at the same time you open this folder in file explorer. Windows wants to create a thumbnail immediately and lock the file. At the same time, your app tries to replace the locked image to some other place. You will receive an exception if you don't use retry policy.
  • CAD bloke
    CAD bloke almost 7 years
    agreed. AutoCAD is a use-case for this sort of thing. When it saves a file it 1. saves the current drawing as a temp file, 2. deletes the old *.bak backup file, 3. renames the *.dwg file to *.bak, 4. renames the new temp file as *.dwg. At no stage does it check for write locks so it often fails on file systems and networks with a lot of latency. Someone should point them at this page.
  • Harry Johnston
    Harry Johnston over 6 years
    You can't use this API without first opening the file, at which point you no longer need to.
  • Harry Johnston
    Harry Johnston over 6 years
    Requires all the processes that are using the file to cooperate. Unlikely to be applicable to the OPs original problem.
  • danny117
    danny117 about 6 years
    I do something like this instead of delay I schedule a future task.
  • Vinney Kelly
    Vinney Kelly about 6 years
    Aside from the race condition mentioned by @akousmata and also triggering the Daily WTF scrutiny, there's a much more practical issue that is this caused the file to be opened, closed, and then presumably re-opened again, once the file is determined to be accessible. While this is a relatively small overhead, it doubles your trips to disk. It would be much more efficient to utilize the try/catch on the actual operation being performed.
  • PJRobot
    PJRobot about 6 years
    Thanks for this, works perfectly well for my application (the race issue is not pertinent): external process is instructed to generate file, file is locked status polled, file is read, file is deleted, repeat.
  • Mr. TA
    Mr. TA almost 6 years
    This kind of file check is usually bad, due to all of the previously mentioned reasons, like race conditions, security vulnerabilities, etc. But sometimes, this is the right solution. In my case, I'm converting a WAV to MP3 using lame.exe, but only after another program is done writing to WAV file. There are no security concerns, nor other programs trying to open the same file.
  • freedeveloper
    freedeveloper over 5 years
    Precisely I got this problem because a windows service with FileSystemWatcher try to read the file before the process closed it.
  • webs
    webs over 5 years
    what about you give us an example we can copy and paste to our vb code?
  • Tyron78
    Tyron78 over 5 years
    Don't know if this post is still being monitored, but I'll give it a try: we are using a quite similar code (possibly it's yours) and it works fine for small files. But recently we are facing a problem when it comes to processing very large files (several GB): Files are copied from server A to server B, where we fetch them and copy them to Folder X, which is our processes input folder. From time to time our process copies a file to folder X even if this file has not yet been completely copied from Server A to Server B - and I can't find out WHY!!! Any help would be highly appreciated.
  • Michal
    Michal over 4 years
    In addition to race conditions described above this "check" is unusable for me because it actually blocks the file for some amount of time if it is not locked. So other apps/threads may raise an exception while trying to access the file. Better to use Restart Manager API, see e.g. stackoverflow.com/questions/1304/…
  • TheLastGIS
    TheLastGIS about 4 years
    Schrodinger's file.
  • BitLauncher
    BitLauncher about 3 years
    Tried it just before (copying a large file from local harddisk to a virtual drive on a virtual server (1 minute) - trying to detect end of that copying with attempts of File.Move() - but it failed! Now file exists in both directories... and it attemted it to copy 3 times at the end...
  • Boppity Bop
    Boppity Bop about 3 years
    this could be a very interesting solution if it had a sample code. the link you provided is now void..
  • Boppity Bop
    Boppity Bop about 3 years
    IsFileBeingUsed - from the accepted answer. he is just offering a way how to use it if you want to get access to the file eventually.. nothing wrong with this answer.
  • Azelski
    Azelski almost 3 years
    Best answer so far. Working for locked files only, not general IO exceptions.
  • Debotos Das
    Debotos Das almost 3 years
    Does anyone know the solution in node.js(Specifically in electron.js)?
  • CodeOrElse
    CodeOrElse almost 3 years
    "Do the operation instead, then handle the exception". Sure, if it's the one file. In my case I need to process a number of files, but if one of them is in use, nothing at all should be done and the user notified. So I need to check all files first, then if all is ok, go ahead and perform the operations. Race-condition? I still handle any exceptions when doing the actual operations so I don't see the issue there.
  • JohnLBevan
    JohnLBevan over 2 years
    FYI: RE: The point about recursion; you could just use add while(!cancellationToken.IsCancellationRequested){/* your try catch blocks here */} cancellationToken.ThrowIfCancellationRequested(); around your existing code to avoid the need for recursion.