File Lock and Unlock in C# .NET

File Lock and Unlock in C How to lock file

Today in this article we shall see the simple and easy approach of How to perform File Lock and Unlock in C# .NET when using it for reading or writing aka performing an update.

The discussed approach is very useful while dealing with any size of the file (.TXT or .CSV or .XLSX) where you need a temporary lock on a file so that other resources can not use it. This could be a legitimate use case for many requirements. It’s also important to write to file in a thread-safe manner.

In this article, we will cover when there is a need to lock files at the time of reading the data and when writing the data to a file.

Today in this article, we will cover below aspects,

For demonstration purposes, I have used a very simple example here.

Let’s say I have a Text file that I am creating using some process. I want this file to be locked until the file generation is completed is done.

lock file in C lock file writing c write to file in a thread safe manner

Below is simple logic which reads the file.

Lock a file while reading the file data – Approach 1

If you would lock a file while reading a file then it is pretty simple to open a file and perform read operations using the below code as explained.

In the below code, we are reading the file using the FileStream Open method which lets you open FileStream on the specified path, with the specified mode.

Setting up FileShare.None will perform below,

  • Declines sharing of the current file.
  • Any request to open the file will fail until the file is closed.

Let’s see below complete example,

 private static void ReadFile(string filePath)
        {
            const int MAX_BUFFER = 1048576; //1MB 
            byte[] buffer = new byte[MAX_BUFFER];
            int bytesRead;
            int noOfFiles = 0;
            using (FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
            using (BufferedStream bs = new BufferedStream(fs))
            {
                while ((bytesRead = bs.Read(buffer, 0, MAX_BUFFER)) != 0) //reading 1mb chunks at a time
                {
                    noOfFiles++;
                    //Let's create a small size file using the data. Or Pass this data for any further processing.

                    File.WriteAllBytes($"Test{noOfFiles}.txt", buffer);
                }
            }
        }

Lock a file while Reading/Writing the file data – Approach 2

Lock a file in C# using File.Lock() method . The lock method let you lock a file so another process cannot access the file. This works even if it has read/write access to the file.

You can lock a file while reading the below simple code,

//Good
using (FileStream stream = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                stream.Lock(0, stream.Length);

                /// You logic here////
            }

In the above method, we can call File.Open to deal a file for reading or writing operations.

Here we are exclusively locking out other processes or threads from accessing the file while you are using it.

When you are done with your operations on the file, code goes out of “using” statements thereby closing any file handle open and releasing it for others to use your file.

Lock a file while Writing to File data – Thread safety – Approach 3

If you ever need to lock a file while writing the data, you can use the below logic to perform the same.

Below we are maintaining synchronization on the file using the lock.

 public class WiteToFileUsingLock
    {
        public string Filepath { get; set; }
        private static object lockerFile = new Object();

        public void WriteToFile(StringBuilder text)
        {
            lock (lockerFile)
            {
                using (FileStream file = new FileStream(Filepath, FileMode.Append, FileAccess.Write, FileShare.Read))
                using (StreamWriter writer = new StreamWriter(file, Encoding.Unicode))
                {
                    writer.Write(text.ToString());
                }
            }

        }
    }

Above Lock exclusively locks the section of code dealing with files until the stream is written to a file and closed.

References:

That’s all! Happy coding!

Does this help you fix your issue?

Do you have any better solutions or suggestions? Please sound off your comments below.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



2 thoughts on “How to File Lock and Unlock in C# .NET

    1. Hi Alexander- Thanks for your query. Have you tried using an explicit lock on an object using Lock(..) as discussed in Approach 3? TextFieldParser seems doesn’t have direct support on file access properties like FileStreams classes etc.

Leave a Reply

Your email address will not be published. Required fields are marked *