Lect Note On Chapter 4 - Part I - File I-O
Lect Note On Chapter 4 - Part I - File I-O
The argument “C:\Windows” assume that the path passed into the constructor
already exists on the physical machine.
Otherwise, attempting to interact with a nonexistent directory result in
System.IO.DirectoryNotFoundException error.
The following will create a director in the specified location:
// Bind to a nonexistent directory, then create it.
DirectoryInfo dir3 = new DirectoryInfo(@"C:\MyCode\Testing");
dir3.Create();
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Directory(Info) *****\n");
ShowWindowsDirectoryInfo();
Console.ReadLine();
}
static void ShowWindowsDirectoryInfo()
{ // Dump directory information.
DirectoryInfo dir = new DirectoryInfo(@"C:\Windows");
Console.WriteLine("***** Directory Info *****");
Console.WriteLine("FullName: {0}", dir.FullName);
Console.WriteLine("Name: {0}", dir.Name);
Console.WriteLine("Parent: {0}", dir.Parent);
Console.WriteLine("Creation: {0}", dir.CreationTime);
Console.WriteLine("Attributes: {0}", dir.Attributes);
Console.WriteLine("Root: {0}", dir.Root);
Console.WriteLine("**************************\n"); }
}
Organized by Teshome A. Page 4
Enumerating Files with the DirectoryInfo Type
class Program
{
static void Main(string[] args) {
Console.WriteLine("***** Fun with DriveInfo *****\n");
// Get info regarding all drives.
DriveInfo[] myDrives = DriveInfo.GetDrives();
// Now print drive stats.
foreach(DriveInfo d in myDrives)
{ Console.WriteLine("Name: {0}", d.Name); Console.WriteLine("Type: {0}",
d.DriveType);
// Check to see whether the drive is mounted.
if (d.IsReady) {
Console.WriteLine("Free space: {0}", d.TotalFreeSpace);
Console.WriteLine("Format: {0}", d.DriveFormat);
Console.WriteLine("Label: {0}", d.VolumeLabel);
Console.WriteLine();
}
} Console.ReadLine();
}}
At this point, you have investigated some core behaviors of the Directory,
DirectoryInfo, and DriveInfo classes. Next, you’ll learn how to create, open, close,
and destroy the files that populate a given directory.
Organized by Teshome A. Page 7
Working with the FileInfo Class
The FileInfo class allows to obtain details regarding existing files on your hard
drive (time created, size, file attributes, and so forth) and aids in the creation,
copying, moving, and destruction of files.
FileInfo class contain functionality inherited from FileSystemInfo + its own.
The first way you can create a file handle is to make use of the FileInfo.Create()
method:
Notice that the FileInfo.Create() method returns a FileStream type, which exposes
synchronous and asynchronous write/read operations to/from the underlying file
The FileStream object returned by FileInfo.Create() grants full read/write access to
all users.
At the end make sure to close down the handle to release the underlying
unmanaged resources of the stream.
The first parameter specifies the general flavor of the I/O request (e.g., make a
new file, open an existing file, append to a file, etc.), which is specified using
the FileMode enumeration
Append Opens a file, moves to the end of the file, and begins write
operations (this flag can only be used with a write-only
stream). If the file does not exist, a new file is created.
The second parameter, a value from the FileAccess enumeration, is used to determine
the read/write behavior of the underlying stream:
The third parameter, FileShare, which specifies how the file is to be shared
among other file handlers.
}}
Clearly, when you wish to quickly obtain a file handle, the File type will save you
some keystrokes.
Close() Closes the current stream and releases any resources (such
as sockets and file handles) associated with the current
stream. Internally, this method is aliased to the Dispose()
method; therefore “closing a stream” is functionally
equivalent to “disposing a stream.”
Read(), ReadByte() Read a sequence of bytes (or a single byte) from the current
stream and advance the current position in the stream by
the number of bytes read.
Close() This method closes the writer and frees any associated resources.
In the process, the buffer is automatically flushed (again,
this member is functionally equivalent to calling the Dispose()
method).
Flush() This method clears all buffers for the current writer and causes
any buffered data to be written to the underlying device,
but does not close the writer.
NewLine This property indicates the newline constant for the derived writer
class. The default line terminator for the Windows OS is a
carriage return followed by a line feed (\r\n).
Write() This overloaded method writes data to the text stream without a
newline constant.
WriteLine() This overloaded method writes data to the text stream with a
newline constant.
Note: The last two members of the TextWriter class probably look familiar to you.
If you recall, the System.Console type has Write() and WriteLine() members that
push textual data to the standard output device.
In fact, the Console.In property wraps a TextWriter, and the Console.Out property
wraps a TextReader.
To see the StreamWriter type in action, create a new Console Application named
StreamWriterReaderApp.
The following Main() method creates a new file named reminders.txt using the
File.CreateText() method.
Using the obtained StreamWriter object, you add some textual data to the new file,
as shown here:
Peek() Returns the next available character without actually changing the
position of the reader. A value of -1 indicates you are at the end of
the stream.
ReadBlock() Reads a maximum of count characters from the current stream and
writes the data to a buffer, beginning at index.
ReadLine() Reads a line of characters from the current stream and returns the
data as a string (a null string indicates EOF).
ReadToEnd() Reads all characters from the current position to the end of the
stream and returns them as a single string.
Illustration: read in the textual data from the reminders.txt file as shown here:
Once you run the program, you will see the character data within reminders.txt
displayed to the console.
One of the slightly confusing aspects of working with the types within System.IO
is that you can often achieve an identical result using numerous approaches.
For example, you have already seen that you can obtain a StreamWriter via the
File or FileInfo type using the CreateText() method.
In reality, there is yet another way in which you can work with StreamWriters and
StreamReaders: create them directly.
For example, the current application could be retrofitted as follows:
Because StringWriter and StreamWriter both derive from the same base class
(TextWriter), the writing logic is more or less identical.
However, given that nature of StringWriter, be aware that this class allows you to
extract a System.Text.StringBuilder object via the GetStringBuilder() method:
When you wish to read from a stream of character data, make use of the
corresponding StringReader type, which (as you would expect) functions
identically to the related StreamReader class.
In fact, the StringReader class does nothing more than override the inherited
members to read from a block of character data, rather than a file, as shown here:
PeekChar() This method returns the next available character without actually
advancing the position in the stream.
Read() This method reads a given set of bytes or characters and stores
them in the incoming array.
Organized by Teshome A. Page 23
ReadXXXX() The BinaryReader class defines numerous read methods that grab
the next type from the stream (ReadBoolean(), ReadByte(),
ReadInt32(), and so forth).