Skip to Main Content
C# Cookbook, 2nd Edition
book

C# Cookbook, 2nd Edition

by Jay Hilyard, Stephen Teilhet
January 2006
Intermediate to advanced content levelIntermediate to advanced
1184 pages
43h 23m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook, 2nd Edition
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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Stephen Teilhet, Jay Hilyard
C# Cookbook

C# Cookbook

Joe Mayo
Head First C#, 4th Edition

Head First C#, 4th Edition

Andrew Stellman, Jennifer Greene

Publisher Resources

ISBN: 0596100639Supplemental ContentCatalog PageErrata