Namespaces in the .NET Framework
The .NET Framework provides common language services to a variety of application development tools. The classes in the framework provide an interface to the common language runtime, the operating system, and the network.
System.IO Namespace
The System.IO namespace is important because it contains many classes that allow an application to perform input and output (I/O) operations in various ways through the file system.
The System.IO namespace also provides classes that allow an application to perform input and output operations on files and directories.
The System.IO namespace is large and cannot be explained in detail here. However, the following list gives an indication of the facilities available:
· The File and Directory classes allow an application to create, delete, and manipulate directories and files.
· The StreamReader and StreamWriter classes enable a program to access file contents as a stream of bytes or characters.
· The FileStream class can be used to provide random access to files.
· The BinaryReader and BinaryWriter classes provide a way to read and write primitive data types as binary values.
System.IO Example
The following example shows how a file can be opened and read as a stream. The example is not meant to illustrate all of the possible ways in which the System.IO namespace can be used, but does show how you can perform a simple file copy operation.
using System;
using System.IO; // Use IO namespace
// ...
StreamReader reader = new StreamReader("infile.txt");
// Text in from file
StreamWriter writer = new StreamWriter("outfile.txt");
// Text out to file
string line;
while ((line = reader.ReadLine( )) != null)
{
writer.WriteLine(line);
}
reader.Close( );
writer.Close( );
To open a file for reading, the code in the example creates a new StreamReader object and passes the name of the file that needs to be opened in the constructor. Similarly, to open a file for writing, the example creates a new StreamWriter object and passes the output file name in its constructor. In the example, the file names are hard-coded, but they could also be string variables.
The example program copies a file by reading one line at a time from the input stream and writing that line to the output stream.
ReadLine and WriteLine might look familiar. The Console class has two static methods of that name. In the example, the methods are instance methods of the StreamReader and StreamWriter classes, respectively.
For more information about the System.IO namespace, search for "System.IO namespace" in the .NET Framework SDK Help documents.