O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required