Click here to Skip to main content
11,720,785 members (72,480 online)
Click here to Skip to main content

Tagged as

C# FileStream Lock. How to wait for a file to get released and lock safely.

, 3 Mar 2011 CPOL 45.5K 12
Rate this:
Please Sign up or sign in to vote.
FileStream has Lock and Unlock methods, but no way to see if file was unlocked by another process.
Let's say we have a file - the one to be used with multiple processes.

I start with an assumption that file gets Write locked to get changed. If that is not the case for you, then my approach will not work. So if it sounds reasonable for you, then see the solution.

public static void Lock(string path, Action<FileStream> action)
{
    var autoResetEvent = new AutoResetEvent(false);
 
    while(true)
    {
        try
        {
            using (var file = File.Open(path,
                                        FileMode.OpenOrCreate,
                                        FileAccess.ReadWrite,
                                        FileShare.Write))
            {
                action(file);
                break;
            }
        }
        catch (IOException)
        {
            var fileSystemWatcher =
                new FileSystemWatcher(Path.GetDirectoryName(path))
                        {
                            EnableRaisingEvents = true
                        };
 
            fileSystemWatcher.Changed +=
                (o, e) =>
                    {
                        if(Path.GetFullPath(e.FullPath) == Path.GetFullPath(path))
                        {
                            autoResetEvent.Set();
                        }
                    };
 
            autoResetEvent.WaitOne();
        }
    }
}

So as you can see, we do an infinite loop which exits only on non IOException or when the block finishes successfully.

To wait and not consume 100% CPU AutoResetEvent which gets Set by FileSystemWatcher.Changed event.

So the flow looks like that:

1) We try to open the file
2) If we have an IOException, we wait until the file gets changed
3) We try to open file again, if failed - wait again
4) If file opened successfully, we perform an action passed as a parameter

You should carefully handle IOException inside your action. See the example:

FileLocker.Lock(@"c:\file",
        (f) =>
            {
                try
                {
                    f.Write(buf, 0, buf.Length);
                }
                catch(IOException ioe)
                {
// handle IOException
                }
            });

If you have any ideas on how to improve the solution, feel free to comment.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Member 7722695
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

 
GeneralGreat code! Pin
Mladen Stanisic23-Oct-14 8:58
memberMladen Stanisic23-Oct-14 8:58 
QuestionI modify your code slightly to fit my needs. Code provided... Pin
Eric Ouellet19-Oct-12 6:00
memberEric Ouellet19-Oct-12 6:00 
GeneralMy vote of 5 Pin
Eric Ouellet19-Oct-12 5:50
memberEric Ouellet19-Oct-12 5:50 
GeneralI agree, maybe adding a TimeSpan MaxWaitTime in order to all... Pin
hoernchenmeister23-Mar-11 4:21
memberhoernchenmeister23-Mar-11 4:21 
GeneralWhile(true) is never a good practise in my opinion. Pin
JV99993-Mar-11 22:17
memberJV99993-Mar-11 22:17 
GeneralFYI Pin
Johnny J.6-Mar-11 20:32
memberJohnny J.6-Mar-11 20:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150901.1 | Last Updated 3 Mar 2011
Article Copyright 2011 by Member 7722695
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid