• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 446
  • Last Modified:

Checking a particular files locking status in C#

Hi there;

I want to check a particular file's locking status in C#.

But I am not sure of the accuracy of the code, moreover I need to find out the file is locked or not for every 5000 ms.

Here is the code, you can check for.

Kind regards.

P.S. A C++ version of this question is ongoing.

Let me enhance this; when my c# application checks for the locking, is it locking the file while checking it? A bitter question for me...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;
using System.Runtime.InteropServices;

namespace LockerConsoleApplication2
{
    class FileManager
    {
        public string _fileName;

        private int _numberOfTries;

        private int _timeIntervalBetweenTries;

        public FileStream GetStream(FileAccess fileAccess)
        {
            var tries = 0;
            while (true)
            {
                try
                {
                    Console.WriteLine("OK");
                    return File.Open(_fileName, FileMode.Open, fileAccess, FileShare.None);                    
                }
                catch (IOException e)
                {
                    if (!IsFileLocked(e))
                        throw;
                    if (++tries > _numberOfTries)
                        throw new Exception("The file is locked too long: " + e.Message, e);
                    Thread.Sleep(_timeIntervalBetweenTries);
                }
            }
        }

        public static bool IsFileLocked(IOException exception)
        {
            int errorCode = Marshal.GetHRForException(exception) & ((1 << 16) - 1);
            return errorCode == 32 || errorCode == 33;
        }

        // other code

    }
    class Program
    {

        static void Main(string[] args)
        {
            FileManager fm = new FileManager();
            fm._fileName = @"C:\MYFILE.BIN";
            fm.GetStream(FileAccess.Read);
            FileManager.IsFileLocked(new IOException());
        }
    }
}

Open in new window

0
jazzIIIlove
Asked:
jazzIIIlove
  • 6
  • 5
5 Solutions
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Is it locking the file?  Yes, because you open the stream with FileShare.None:
http://msdn.microsoft.com/en-us/library/system.io.fileshare.aspx

    "None --> Declines sharing of the current file. Any request to open the file (by this process or another process) will fail until the file is closed."
0
 
jazzIIIloveAuthor Commented:
So, in fact my code is a crap to check whether it's used or not.

True?
If so, any ways to determine this in C#?

Regards.
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Just depends on the situation...

If the file is "in use" by someone else when you check it, then you will indeed report back that it is "unavailable" because you will fail to open it since the FileShare.None flag won't let you open it in an exclusive mode.

While you have that stream open, though, other apps will fail when they try to open the file.  You can open and close the stream as quickly as possible in an attempt to avoid this but it isn't foolproof.

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
jazzIIIloveAuthor Commented:
So, the question is that how can i check this with a C# code properly?

Regards.
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
That depends on the question...

Which question better suits your situation?
(1) Are there any other processes using this file?
(2) Can I open this file exclusively?

The two are not quite the same.
0
 
jazzIIIloveAuthor Commented:
Hi there;

I think, 1. covers 2. Is it true?
but I think my code covers only 2. Is it true?

Regards.
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
If you can do (2), then (1) is false.

The question is, do you want to know (1) without doing (2)?
0
 
jazzIIIloveAuthor Commented:
Yep.

Regards.
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
0
 
jazzIIIloveAuthor Commented:
Extremely good link, what about vice-versa case? Any snippets or links?

Regards.
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
You're already doing that via Open and FileShare.None.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 6
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now