By Dawsy


2009-05-18 06:37:40 8 Comments

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?

17 comments

@Tadej 2019-04-09 12:48:56

Would something like this help?

var fileWasWrittenSuccessfully = false;
while (fileWasWrittenSuccessfully == false)
{
    try
    {
        lock (new Object())
        {
            using (StreamWriter streamWriter = new StreamWriter(filepath.txt"), true))
            {
                streamWriter.WriteLine("text");
            }
        }

        fileWasWrittenSuccessfully = true;
    }
    catch (Exception)
    {

    }
}

@Bernhard 2018-10-09 06:56:20

Aside from working 3-liners and just for reference: If you want the full blown information - there is a little project on Microsoft Dev Center:

https://code.msdn.microsoft.com/windowsapps/How-to-know-the-process-704839f4

From the Introduction:

The C# sample code developed in .NET Framework 4.0 would help in finding out which is the process that is having a lock on a file. RmStartSession function which is included in rstrtmgr.dll has been used to create a restart manager session and according to the return result a new instance of Win32Exception object is created. After registering the resources to a Restart Manager session via RmRegisterRescources function, RmGetList function is invoked to check what are the applications are using a particular file by enumerating the RM_PROCESS_INFO array.

It works by connecting to the "Restart Manager Session".

The Restart Manager uses the list of resources registered with the session to determine which applications and services must be shut down and restarted. Resources can be identified by filenames, service short names, or RM_UNIQUE_PROCESS structures that describe running applications.

It might be a little overengineered for your particular needs... But if that is what you want, go ahead and grab the vs-project.

@Vinney Kelly 2018-04-05 12:07:23

I'm interested to see if this triggers any WTF reflexes. I have a process which creates and subsequently launches a PDF document from a console app. However, I was dealing with a frailty where if the user were to run the process multiple times, generating the same file without first closing the previously generated file, the app would throw an exception and die. This was a rather frequent occurrence because file names are based on sales quote numbers.

Rather than failing in such an ungraceful manner, I decided to rely on auto-incremented file versioning:

private static string WriteFileToDisk(byte[] data, string fileName, int version = 0)
{
    try
    {
        var versionExtension = version > 0 ? $"_{version:000}" : string.Empty;
        var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{fileName}{versionExtension}.pdf");
        using (var writer = new FileStream(filePath, FileMode.Create))
        {
            writer.Write(data, 0, data.Length);
        }
        return filePath;
    }
    catch (IOException)
    {
        return WriteFileToDisk(data, fileName, ++version);
    }
}

Probably some more care can be given to the catch block to ensure I'm catching the correct IOException(s). I'll probably also clear out the app storage on startup since these files are intended to be temporary anyways.

I realize this goes beyond the scope of the OP's question of simply checking if the file is in use but this was indeed the problem I was looking to solve when I arrived here so perhaps it will be useful to someone else.

@Tomasz ┼╗muda 2017-09-07 10:44:08

You can use my library for accessing files from multiple apps.

You can install it from nuget: Install-Package Xabe.FileLock

If you want more information about it check https://github.com/tomaszzmuda/Xabe.FileLock

ILock fileLock = new FileLock(file);
if(fileLock.Acquire(TimeSpan.FromSeconds(15), true))
{
    using(fileLock)
    {
        // file operations here
    }
}

fileLock.Acquire method will return true only if can lock file exclusive for this object. But app which uploading file must do it in file lock too. If object is inaccessible metod returns false.

@paper1111 2017-09-07 10:45:25

Please don't just post some tool or library as an answer. At least demonstrate how it solves the problem in the answer itself.

@Tomasz ┼╗muda 2017-09-07 10:50:04

Added demo :) Sorry @paper1111

@Harry Johnston 2017-09-07 21:17:32

Requires all the processes that are using the file to cooperate. Unlikely to be applicable to the OPs original problem.

@cdiggins 2016-08-22 20:41:25

Here is some code that as far as I can best tell does the same thing as the accepted answer but with less code:

    public static bool IsFileLocked(string file)
    {
        try
        {
            using (var stream = File.OpenRead(file))
                return false;
        }
        catch (IOException)
        {
            return true;
        }        
    }

However I think it is more robust to do it in the following manner:

    public static void TryToDoWithFileStream(string file, Action<FileStream> action, 
        int count, int msecTimeOut)
    {
        FileStream stream = null;
        for (var i = 0; i < count; ++i)
        {
            try
            {
                stream = File.OpenRead(file);
                break;
            }
            catch (IOException)
            {
                Thread.Sleep(msecTimeOut);
            }
        }
        action(stream);
    }

@Ivan Branets 2015-10-20 12:33:01

You can return a task which gives you a stream as soon as it becomes available. It's a simplified solution, but it is a good starting point. It's thread safe.

private async Task<Stream> GetStreamAsync()
{
    try
    {
        return new FileStream("sample.mp3", FileMode.Open, FileAccess.Write);
    }
    catch (IOException)
    {
        await Task.Delay(TimeSpan.FromSeconds(1));
        return await GetStreamAsync();
    }
}

You can use this stream as usual:

using (var stream = await FileStreamGetter.GetStreamAsync())
{
    Console.WriteLine(stream.Length);
}

@CAD bloke 2017-07-24 11:14:05

How many seconds until a stack overflow from the recursion in GetStreamAsync()?

@Ivan Branets 2017-07-26 08:51:07

@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 2017-07-26 08:59:46

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 2017-07-26 12:25:17

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 2017-07-31 13:16:47

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 2017-07-31 21:52:12

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.

@danny117 2018-02-19 18:36:23

I do something like this instead of delay I schedule a future task.

@ChrisW 2009-06-02 01:20:19

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. While this solution works because trying to check with FileAccess.Read will fail if the file has a Write or Read lock on it, however, this solution will not work if the file doesn't have a Write or Read lock on it, i.e. it has been opened (for reading or writing) with FileShare.Read or FileShare.Write access.

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)
{
    FileStream stream = null;

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None);
    }
    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;
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }

    //file is not locked
    return false;
}

@adeel825 2010-01-29 01:28:30

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 2010-05-26 15:56:46

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 2010-05-26 15:58:41

-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.

@Clément 2011-03-30 16:11:46

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 2011-03-31 06:00:39

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().

@Matthew 2011-08-10 18:09:29

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 2011-11-10 11:45:28

Matthew, the finally is always called, whatever happens. Always. Dot. :)

@Louis Rhys 2012-01-30 03:52:48

@adeel825 will changing it to read cause any side-effect? For example, being unable to detect files that are only write-locked?

@Wiebe Tijsma 2012-02-08 13:47:46

@SoMoS actually, the finally block is NOT always executed, there's some exceptions that stop your flow (think ThreadAbortException, StackOverflowException, OutOfMemoryException)

@Ignacio Soler Garcia 2012-02-08 21:33:00

@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 2012-02-14 15:00:16

@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/…

@itsho 2012-06-29 15:55:15

small note: you might consider use using block for automatic disposing, or at least, dispose the stream by yourself.

@Manuzor 2012-07-04 11:06:47

I think this is a great answer. I'm using this as an extension method á la public static bool IsLocked(this FileInfo file) {/*...*/}.

@Pierre Lebeaupin 2013-03-11 13:15:48

@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/…

@Fred Larson 2013-03-11 14:10:59

@PierreLebeaupin: And why wouldn't that be alarming?

@jcolebrand 2013-03-11 14:26:02

@FredLarson Random downvotes vs explained downvotes?

@Lee Louviere 2013-03-11 15:12:40

@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!

@DiskJunky 2013-03-12 13:00:44

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

@Jeremy 2014-04-29 20:41:23

@Jeremy 2014-04-29 20:43:03

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/…

@jheriko 2014-10-28 17:42:10

"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 2014-11-03 13:51:45

What if you don't have write access to the folder that the file is in?

@Hans Passant 2015-05-03 23:44:58

@Paul Taylor 2015-08-27 10:35:12

The stream object doesn't get Disposed in this solution. Better to wrap it in a using statement.

@Frédéric 2015-09-25 07:37:01

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 2015-09-25 08:01:51

@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 2015-10-15 14:29:57

I've added a more comprehensive way to check for file locks and documented the limitations below: stackoverflow.com/a/33150038

@BloodyRain2k 2016-06-24 03:23:17

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 2016-07-18 20:42:31

Why is this method virtual, not static?

@akousmata 2017-06-26 16:17:39

-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.

@Vinney Kelly 2018-04-05 12:15:25

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 2018-04-11 13:45:41

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 2018-05-29 19:23:57

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.

@webs 2018-10-20 10:32:50

what about you give us an example we can copy and paste to our vb code?

@Tyron78 2018-10-24 15:27:02

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.

@rboy 2015-10-15 13:34:59

The accepted answers above suffer an issue where if file has been opened for writing with a FileShare.Read mode or if the file has a Read-Only attribute the code will not work. This modified solution works most reliably, with two things to keep in mind (as true for the accepted solution also):

  1. It will not work for files that has been opened with a write share mode
  2. This does not take into account threading issues so you will need to lock it down or handle threading issues separately.

Keeping the above in mind, this checks if the file is either locked for writing or locked to prevent reading:

public static bool FileLocked(string FileName)
{
    FileStream fs = null;

    try
    {
        // NOTE: This doesn't handle situations where file is opened for writing by another process but put into write shared mode, it will not throw an exception and won't show it as write locked
        fs = File.Open(FileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None); // If we can't open file for reading and writing then it's locked by another process for writing
    }
    catch (UnauthorizedAccessException) // https://msdn.microsoft.com/en-us/library/y973b725(v=vs.110).aspx
    {
        // This is because the file is Read-Only and we tried to open in ReadWrite mode, now try to open in Read only mode
        try
        {
            fs = File.Open(FileName, FileMode.Open, FileAccess.Read, FileShare.None);
        }
        catch (Exception)
        {
            return true; // This file has been locked, we can't even open it to read
        }
    }
    catch (Exception)
    {
        return true; // This file has been locked
    }
    finally
    {
        if (fs != null)
            fs.Close();
    }
    return false;
}

@Harry Johnston 2015-10-16 19:57:42

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!

@rboy 2015-10-17 03:03:43

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.

@kernowcode 2015-05-26 15:29:09

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);
}

@Jeremy Thompson 2012-06-16 02:31:09

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");

@Kris 2013-03-11 21:27:45

I would upvote if there weren't so many "magic numbers" in there en.wikipedia.org/wiki/Magic_number_(programming)

@Jeremy Thompson 2013-03-15 01:54:39

@Kris meh cant you read bit shifts, lol

@Kris 2013-03-15 09:35:17

I was referring to the errorCode comparisons, not the bit shifts. though now you mention it...

@Jeremy Thompson 2013-03-15 23:35:51

yeah you are right, I made them constants...

@Askolein 2013-04-22 14:31:53

Your Catch should be on IOException, instead of on general Exception and then a test on type.

@Askolein 2013-06-18 13:48:17

@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.

@shindigo 2014-04-18 20:33:34

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 Thompson 2015-04-20 00:41:20

@RenniePet I fixed it and removed the comment, sort of pissed me off though that one person obviously has been downvoting everyone else's answers... I just got the sportsmanship badge yesterday and that's the better thing to do..

@RenniePet 2015-04-20 01:00:40

Thanks for fixes, I've given you a plus vote now. But I think the if and close statements in the using block are actually in error - ReSharper says that "stream" can never be null. Congrats on your new badge.

@Jeremy Thompson 2016-09-05 02:22:14

If you want to open the file while another process has it open, specify FileAccess fileAccess = FileAccess.Read, FileShare fileShare = FileShare.ReadWrite

@BartoszKP 2017-04-18 15:16:27

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.

@Drag and Drop 2018-01-04 15:57:37

I sometimes also use fileStream.Close();. Is there really a case or a race condition where this will have an effect?

@atlaste 2014-09-02 10:31:24

In my experience, you usually want to do this, then 'protect' your files to do something fancy and then use the 'protected' files. If you have just one file you want to use like this, you can use the trick that's explained in the answer by Jeremy Thompson. However, if you attempt to do this on lots of files (say, for example when you're writing an installer), you're in for quite a bit of hurt.

A very elegant way this can be solved is by using the fact that your file system will not allow you to change a folder name if one of the files there it's being used. Keep the folder in the same file system and it'll work like a charm.

Do note that you should be aware of the obvious ways this can be exploited. After all, the files won't be locked. Also, be aware that there are other reasons that can result in your Move operation to fail. Obviously proper error handling (MSDN) can help out here.

var originalFolder = @"c:\myHugeCollectionOfFiles"; // your folder name here
var someFolder = Path.Combine(originalFolder, "..", Guid.NewGuid().ToString("N"));

try
{
    Directory.Move(originalFolder, someFolder);

    // Use files
}
catch // TODO: proper exception handling
{
    // Inform user, take action
}
finally
{
    Directory.Move(someFolder, originalFolder);
}

For individual files I'd stick with the locking suggestion posted by Jeremy Thompson.

@Jeremy Thompson 2014-11-21 11:02:32

Hi, Since the order of answers changes can you clarify which post above you mean for readers of this popular QA. Thanks.

@atlaste 2014-11-21 11:09:25

@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.

@Spence 2009-05-18 06:57:05

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.
}

@Sedat Kapanoglu 2011-01-04 07:16:05

+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.

@TamusJRoyce 2011-07-31 22:37:20

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 2011-08-01 23:52:55

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.

@Ben Hughes 2012-11-26 08:17:26

People who put usings in try/catch blocks confuse me. Just use a try/catch/finally....

@Spence 2012-11-27 20:01:51

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 2013-01-30 15:50:20

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 2013-01-31 00:27:45

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.

@Harry Johnston 2013-03-12 10:11:55

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?

@Bob 2013-03-13 10:57:56

@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 2013-03-14 02:50:18

@Bob: that comment wasn't part of the answer until yesterday. :-) It makes it a lot clearer.

@Suamere 2014-09-03 22:16:20

@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.

@Frédéric 2015-09-25 07:34:39

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.

@Harry Johnston 2015-10-16 19:56:24

@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.)

@Frédéric 2015-10-16 20:32:07

@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 2015-10-16 20:47:54

@Frederic: it is a poor answer to this particular question. It might be a good answer to a question about launching Excel.

@Spence 2015-10-26 01:06:01

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?

@zzfima 2012-01-17 15:45:31

I use this workaround, but i have a timespan between when i check the file locking with IsFileLocked function and when i open the file. In this timespan some other thread can open the file, so i will get IOException.

So, i added extra code for this. In my case i want load XDocument:

        XDocument xDoc = null;

        while (xDoc == null)
        {
            while (IsFileBeingUsed(_interactionXMLPath))
            {
                Logger.WriteMessage(Logger.LogPrioritet.Warning, "Deserialize can not open XML file. is being used by another process. wait...");
                Thread.Sleep(100);
            }
            try
            {
                xDoc = XDocument.Load(_interactionXMLPath);
            }
            catch
            {
                Logger.WriteMessage(Logger.LogPrioritet.Error, "Load working!!!!!");
            }
        }

What do you think? Can i change some thing? Maybe i did not have to use IsFileBeingUsed function at all?

Thanks

@Kiquenet 2013-07-30 06:01:09

what is IsFileBeingUsed ? source code about IsFileBeingUsed ?

@Julian 2011-08-22 16:01:58

static bool FileInUse(string path)
    {
        try
        {
            using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
            {
                fs.CanWrite
            }
            return false;
        }
        catch (IOException ex)
        {
            return true;
        }
    }

string filePath = "C:\\Documents And Settings\\yourfilename";
bool isFileInUse;

isFileInUse = FileInUse(filePath);

// Then you can do some checking
if (isFileInUse)
   Console.WriteLine("File is in use");
else
   Console.WriteLine("File is not in use");

Hope this helps!

@Lakey 2013-03-25 19:50:23

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.

@Carra 2009-05-18 09:11:04

Try and move/copy the file to a temp dir. If you can, it has no lock and you can safely work in the temp dir without getting locks. Else just try to move it again in x seconds.

@jcolebrand 2013-03-11 14:27:13

What if something locks it right after you move the file?

@Cullub 2014-08-07 17:23:24

@jcolebrand locks what? the one you copied? Or the one you put in the temp dir?

@jcolebrand 2014-08-07 21:07:46

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.

@Karl Johan 2009-05-18 06:52:09

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.

@user219337 2011-07-08 12:29:25

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...

@Ben F 2012-06-20 07:59:51

FileSystemWatcher doesn't handle lots of changes at the same time very well though, so be careful with that.

@devlord 2013-04-22 00:29:23

BTW, have you guys noticed while debugging and watching threads that MS calls their own FSW "FileSystemWather"? What's a wather anyway?

@freedeveloper 2018-08-08 15:09:06

Precisely I got this problem because a windows service with FileSystemWatcher try to read the file before the process closed it.

@Luke Schafer 2009-05-18 06:42:31

the only way I know of is to use the Win32 exclusive lock API which isn't too speedy, but examples exist.

Most people, for a simple solution to this, simply to try/catch/sleep loops.

@Harry Johnston 2017-09-07 21:15:55

You can't use this API without first opening the file, at which point you no longer need to.

Related Questions

Sponsored Content

38 Answered Questions

[SOLVED] How do I check whether a file exists without exceptions?

22 Answered Questions

[SOLVED] Find and restore a deleted file in a Git repository

33 Answered Questions

[SOLVED] How do I create a Java string from the contents of a file?

35 Answered Questions

[SOLVED] How to read a file line-by-line into a list?

27 Answered Questions

[SOLVED] What is the best way to iterate over a dictionary?

  • 2008-09-26 18:20:06
  • Jake Stewart
  • 1352658 View
  • 2250 Score
  • 27 Answer
  • Tags:   c# dictionary loops

17 Answered Questions

[SOLVED] How do I tell if a regular file does not exist in Bash?

  • 2009-03-12 14:48:43
  • Bill the Lizard
  • 2304579 View
  • 2914 Score
  • 17 Answer
  • Tags:   bash file-io scripting

54 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

10 Answered Questions

[SOLVED] Correct way to write line to file?

  • 2011-05-28 05:44:53
  • Yaroslav Bulatov
  • 1824707 View
  • 899 Score
  • 10 Answer
  • Tags:   python file-io

42 Answered Questions

[SOLVED] How to create Excel (.XLS and .XLSX) file in C# without installing Ms Office?

  • 2008-09-29 22:30:28
  • mistrmark
  • 996918 View
  • 1729 Score
  • 42 Answer
  • Tags:   c# .net excel file-io

10 Answered Questions

[SOLVED] Delete a file or folder

Sponsored Content