12.11. Locking Subsections of a File

Problem

You need to read or write data from or to a section of a file, and you want to make sure that no other processes or threads can access, modify, or delete the file until you have finished with it.

Solution

Locking out other processes from accessing your file while you are using it is accomplished through the Lock method of the FileStream class. The following code creates a file from the fileName parameter and writes two lines to it. The entire file is then locked using the Lock method. While the file is locked, the code goes off and does some other processing; when this code returns, the file is closed, thereby unlocking it:

	public static void CreateLockedFile(string fileName)
	{
	    using (FileStream fileStream = new FileStream(fileName,
	              FileMode.Create,
	              FileAccess.ReadWrite,
	              FileShare.ReadWrite))
	    {
	        using (StreamWriter streamWriter = new StreamWriter(fileStream))
	        {
	            streamWriter.WriteLine("The First Line");
	            streamWriter.WriteLine("The Second Line");
	            streamWriter.Flush();

	            try
	            {
	                // Lock all of the file.
	                fileStream.Lock(0, fileStream.Length);

	                // Do some lengthy processing here...
	                Thread.Sleep(1000);
	            }
	            finally
	            {
	                // Make sure we unlock the file.
	                // If a process terminates with part of a file locked or closes
	                // a file that has outstanding locks, the behavior is undefined,
	                // which is MS speak for bad things.
	                fileStream.Un lock(0, fileStream.Length);
	            }

	            streamWriter.WriteLine("The Third Line");
	        }
	    }
	}

Discussion

If a file is opened within your application ...

Get C# 3.0 Cookbook, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.