Login

Username:

Password: 

Join us Now |  Forgot Password? | Forgot UserName?

C#

Learn step by step



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:

ClassDescription
BinaryReaderReads primitive data types as binary values in a specific encoding.
BinaryWriterWrites primitive types in binary to a stream and supports writing strings in a specific encoding.
BufferedStreamAdds a buffering layer to read and write operations on another stream. This class cannot be inherited.
DirectoryExposes static methods for creating, moving, and enumerating through directories and subdirectories. This class cannot be inherited.
DirectoryInfoExposes instance methods for creating, moving, and enumerating through directories and subdirectories. This class cannot be inherited.
DirectoryNotFoundExceptionThe exception that is thrown when part of a file or directory cannot be found.
DriveInfoProvides access to information on a drive.
DriveNotFoundExceptionThe exception that is thrown when trying to access a drive or share that is not available.
EndOfStreamExceptionThe exception that is thrown when reading is attempted past the end of a stream.
ErrorEventArgsProvides data for the Error event.
FileProvides static methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects.
FileFormatExceptionThe 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.
FileInfoProvides 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.
FileLoadExceptionThe exception that is thrown when a managed assembly is found but cannot be loaded.
FileNotFoundExceptionThe exception that is thrown when an attempt to access a file that does not exist on disk fails.
FileStreamStream around a file, supporting both synchronous and asynchronous read and write operations.
FileSystemEventArgsProvides data for the directory events:Changed,Created, Deleted.
FileSystemInfoProvides the base class for both FileInfo and DirectoryInfo objects.
FileSystemWatcherListens to the file system change notifications and raises events when a directory, or file in a directory, changes.
InternalBufferOverflowExceptionThe exception thrown when the internal buffer overflows.
InvalidDataExceptionThe exception that is thrown when a data stream is in an invalid format.
IODescriptionAttributeSets the description visual designers can display when referencing an event, extender, or property.
IOExceptionThe exception that is thrown when an I/O error occurs.
MemoryStreamCreates a stream whose backing store is memory.
PathPerforms operations on String instances that contain file or directory path information. These operations are performed in a cross-platform manner.
PathTooLongExceptionThe exception that is thrown when a path or file name is longer than the system-defined maximum length.
PipeExceptionThrown when an error occurs within a named pipe.
RenamedEventArgsProvides data for the Renamed event.
StreamProvides a generic view of a sequence of bytes.
StreamReaderImplements a TextReader that reads characters from a byte stream in a particular encoding.
StreamWriterImplements a TextWriter for writing characters to a stream in a particular encoding.
StringReaderImplements a TextReader that reads from a string.
StringWriterImplements a TextWriter for writing information to a string. The information is stored in an underlying StringBuilder.
TextReaderRepresents a reader that can read a sequential series of characters.
TextWriterRepresents a writer that can write a sequential series of characters. This class is abstract.
UnmanagedMemoryAccessorProvides random access to unmanaged blocks of memory from managed code.
UnmanagedMemoryStreamProvides 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:

FileStream <object_name> = new FileStream( <file_name>,
<FileMode Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>);

For example, for creating a FileStream object F for reading a file named sample.txt:

FileStream F = new FileStream("sample.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
ParameterDescription
FileMode

The FileMode enumerator defines various methods for opening files. The members of the FileMode enumerator are:

  • Append: It opens an existing file and puts cursor at the end of file, or creates the file, if the file does not exist.
  • Create: It creates a new file.
  • CreateNew: It specifies to the operating system, that it should create a new file.
  • Open: It opens an existing file.
  • OpenOrCreate: It specifies to the operating system that it should open a file if it exists, otherwise it should create a new file.
  • Truncate: It opens an existing file and truncates its size to zero bytes.
FileAccessFileAccess enumerators have members: Read, ReadWrite and Write.
FileShareFileShare enumerators have the following members:
  • Inheritable: It allows a file handle to pass inheritance to the child processes
  • None: It declines sharing of the current file
  • Read: It allows opening the file for reading
  • ReadWrite: It allows opening the file for reading and writing
  • Write: It allows opening the file for writing

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.

namespace mcFileStream
{
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();
}
}
}


Related Videos