
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Watching the Filesystem for Specific Changes to One or More Files or Directories
|
733
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);
// Try to access the locked file...
using (StreamWriter streamWriter2 = new StreamWriter(
new FileStream(fileName,
FileMode.Open,
FileAccess.Write,
FileShare.ReadWrite)))
{
streamWriter2.Write("foo");
fileStream.Unlock(0, fileStream.Length);
streamWriter2.Flush( );
}
}
}
}
no exception is thrown. This is due to the fact that the code closed the FileStream
object that initially locked the entire file. This action also freed all of the locks on the
file that this
FileStream object was holding onto. Since the streamWriter2.
Write("Foo"
) method had written Foo to the stream’s buffer (but had not flushed it),
the string
Foo was still waiting to be flushed and written to the actual file. Keep this
situation in mind when interleaving the opening, locking, and closing of streams.
Mistakes in code sometimes manifest themselves a while after they are written. This
leads to some bugs that are more difficult to track down, so