File and Stream I/O
The System.IO namespace contains types that allow synchronous and asynchronous reading and writing on data streams and files.
The following distinctions help clarify the differences between a file and a stream. A file is an ordered and named collection of a particular sequence of bytes having persistent storage. Therefore, with files, one thinks in terms of directory paths, disk storage, and file and directory names. In contrast, streams provide a way to write and read bytes to and from a backing store that can be one of several storage mediums. Just as there are several backing stores other than disks, there are several kinds of streams other than file streams. For example, there are network, memory, and tape streams.
C# I/O Classes
The System.IO namespace has various class that are used for performing various operation with files, like creating and deleting files, reading from or writing to a file, closing a file etc.
The following table shows some commonly used non-abstract classes in the System.IO namespace:
Class | Description |
---|---|
BinaryReader | Reads primitive data types as binary values in a specific encoding. |
BinaryWriter | Writes primitive types in binary to a stream and supports writing strings in a specific encoding. |
BufferedStream | Adds a buffering layer to read and write operations on another stream. This class cannot be inherited. |
Directory | Exposes static methods for creating, moving, and enumerating through directories and subdirectories. This class cannot be inherited. |
DirectoryInfo | Exposes instance methods for creating, moving, and enumerating through directories and subdirectories. This class cannot be inherited. |
DirectoryNotFoundException | The exception that is thrown when part of a file or directory cannot be found. |
DriveInfo | Provides access to information on a drive. |
DriveNotFoundException | The exception that is thrown when trying to access a drive or share that is not available. |
EndOfStreamException | The exception that is thrown when reading is attempted past the end of a stream. |
ErrorEventArgs | Provides data for the Error event. |
File | Provides static methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects. |
FileFormatException | The exception that is thrown when an input file or a data stream that is supposed to conform to a certain file format specification is malformed. |
FileInfo | Provides properties and instance methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects. This class cannot be inherited. |
FileLoadException | The exception that is thrown when a managed assembly is found but cannot be loaded. |
FileNotFoundException | The exception that is thrown when an attempt to access a file that does not exist on disk fails. |
FileStream | Stream around a file, supporting both synchronous and asynchronous read and write operations. |
FileSystemEventArgs | Provides data for the directory events:Changed,Created, Deleted. |
FileSystemInfo | Provides the base class for both FileInfo and DirectoryInfo objects. |
FileSystemWatcher | Listens to the file system change notifications and raises events when a directory, or file in a directory, changes. |
InternalBufferOverflowException | The exception thrown when the internal buffer overflows. |
InvalidDataException | The exception that is thrown when a data stream is in an invalid format. |
IODescriptionAttribute | Sets the description visual designers can display when referencing an event, extender, or property. |
IOException | The exception that is thrown when an I/O error occurs. |
MemoryStream | Creates a stream whose backing store is memory. |
Path | Performs operations on String instances that contain file or directory path information. These operations are performed in a cross-platform manner. |
PathTooLongException | The exception that is thrown when a path or file name is longer than the system-defined maximum length. |
PipeException | Thrown when an error occurs within a named pipe. |
RenamedEventArgs | Provides data for the Renamed event. |
Stream | Provides a generic view of a sequence of bytes. |
StreamReader | Implements a TextReader that reads characters from a byte stream in a particular encoding. |
StreamWriter | Implements a TextWriter for writing characters to a stream in a particular encoding. |
StringReader | Implements a TextReader that reads from a string. |
StringWriter | Implements a TextWriter for writing information to a string. The information is stored in an underlying StringBuilder. |
TextReader | Represents a reader that can read a sequential series of characters. |
TextWriter | Represents a writer that can write a sequential series of characters. This class is abstract. |
UnmanagedMemoryAccessor | Provides random access to unmanaged blocks of memory from managed code. |
UnmanagedMemoryStream | Provides access to unmanaged blocks of memory from managed code. |
The FileStream Class
The FileStream class in the System.IO namespace helps in reading from, writing to and closing files. This class derives from the abstract class Stream.
You need to create a FileStream object to create a new file or open an existing file. The syntax for creating a FileStream object is as follows:
<FileMode Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>);
For example, for creating a FileStream object F for reading a file named sample.txt:
Parameter | Description |
---|---|
FileMode | The FileMode enumerator defines various methods for opening files. The members of the FileMode enumerator are:
|
FileAccess | FileAccess enumerators have members: Read, ReadWrite and Write. |
FileShare | FileShare enumerators have the following members:
|
The FileStream class is derived from Stream class. This class can be used for reading from and writing to files such as bytes, characters, strings, and other data-type values to a file. Other class I have used in this sample is StreamWriter. The StreamWriter class's Write and WriteLine members write to a file.
In this sample code, I have used FileStream class to create a text file and StreamWrite to write text to the text file.
{
using System;
using System.IO;
public class mcLogFile
{
public static void Main(String[] args)
{
// Create a text file C:\temp\mcb.txt
FileStream fs = new FileStream(@"c:\temp\mcb.txt" , FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter = new StreamWriter(fs);
// Write to the file using StreamWriter class
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.Write(" File Write Operation Starts : ");
m_streamWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString());
m_streamWriter.WriteLine(" First Line : Data is first line \n");
m_streamWriter.WriteLine(" This is next line in the text file. \n ");
m_streamWriter.Flush();
// Read from the file using StreamReader class
// StreamReader m_streamReader = new StreamReader(fs);
// string str = m_streamReader.ReadLine();
}
}
}