
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Locking Subsections of a File
|
731
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( );
// 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");
}
}
}
Discussion
If a file is opened within your application and the FileShare parameter of the
FileStream.Open call is set to FileShare.ReadWrite or FileShare.Write, other code in
your application can view or alter the contents of the file while you are using it. To
handle file access with more granularity, use the
Lock method of the FileStream
object to prevent other code from overwriting all or a portion of your file. Once you
are done with the locked portion of your file, you can call the
Unlock method ...