11.22. Locking Subsections of a File

Problem

You need to read or write data to or from 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 or threads 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 void CreateLockedFile(string fileName)
{
    FileStream fileStream = new FileStream(fileName, 
        FileMode.Create, 
        FileAccess.ReadWrite, 
        FileShare.ReadWrite);
    StreamWriter streamWriter = new StreamWriter(fileStream);

    streamWriter.WriteLine("The First Line");
    streamWriter.WriteLine("The Second Line");
    streamWriter.Flush( );

    // Lock all of the file
    fileStream.Lock(0, fileStream.Length);
 
    // Do some lengthy processing here...
    Thread.Sleep(1000);

    // 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.Unlock(0, fileStream.Length);

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

Discussion

If a file is opened within your ...

Get C# Cookbook 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.