
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Determining Whether a Directory Exists
|
701
class contains a PeekChar method that is very similar to the Peek method in the
StreamReader class. The PeekChar method is used as follows:
using (FileStream fileStream = new FileStream("data.txt", FileMode.Open))
{
BinaryReader binaryReader = new BinaryReader(fileStream);
while (binaryReader.PeekChar( ) != -1)
{
Console.WriteLine(binaryReader.ReadChar( ));
}
}
In this code, the PeekChar method is used to determine when to stop reading values
in the file. This will prevent a costly
EndOfStreamException from being thrown by the
ReadChar method if it tries to read past the end of the file.
See Also
See the “FileStream Class,” “StreamReader Class,” “StreamWriter Class,” “Binary-
Reader Class,” and “BinaryWriter Class” topics in the MSDN documentation.
12.9 Determining Whether a Directory Exists
Problem
You need to determine whether a directory exists prior to creating or performing an
action on that directory.
Solution
Use the static Exists method on the Directory class to determine whether a direc-
tory currently exists:
if (Directory.Exists(@"c:\delete\test"))
{
// Operate on that directory here
}
Discussion
If you try to delete a directory that no longer exists, a System.IO.
DirectoryNotFoundException
will be thrown. This can be handled by catching