Easy Tutorial
❮ Csharp Regular Expressions Csharp Unsafe Codes ❯

File Input and Output in C

A file is a collection of data stored on a disk with a specified name and directory path. When a file is opened for reading or writing, it becomes a stream.

Fundamentally, a stream is a sequence of bytes transmitted over a communication path. There are two main types of streams: input streams and output streams. Input streams are used to read data from a file (read operations), and output streams are used to write data to a file (write operations).

C# I/O Classes

The System.IO namespace contains various classes for performing numerous file operations, such as creating and deleting files, reading from or writing to files, and closing files.

The following table lists some commonly used non-abstract classes in the System.IO namespace:

I/O Class Description
BinaryReader Reads primitive data from a binary stream.
BinaryWriter Writes primitive data in binary format.
BufferedStream Temporary storage for a stream of bytes.
Directory Helps manipulate directory structures.
DirectoryInfo Used for performing operations on directories.
DriveInfo Provides information about drives.
File Helps manipulate files.
FileInfo Used for performing operations on files.
FileStream Used for reading and writing at any location in a file.
MemoryStream Used for random access to streamed data stored in memory.
Path Performs operations on path information.
StreamReader Used for reading characters from a byte stream.
StreamWriter Used for writing characters to a stream.
StringReader Used for reading from a string buffer.
StringWriter Used for writing to a string buffer.

FileStream Class

The FileStream class in the System.IO namespace helps with reading, writing, 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 one. The syntax for creating a FileStream object is as follows:

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

For example, to create a FileStream object F to read a file named sample.txt:

FileStream F = new FileStream("sample.txt", FileMode.Open, FileAccess.Read, FileShare.Read);
Parameter Description
FileMode The FileMode enumeration defines various methods for opening files. Members of the FileMode enumeration include: Append: Opens an existing file and places the cursor at the end of the file. If the file does not exist, it creates one. Create: Creates a new file. If the file already exists, it deletes the old file and creates a new one. CreateNew: Specifies that the operating system should create a new file. If the file already exists, an exception is thrown. Open: Opens an existing file. If the file does not exist, an exception is thrown. OpenOrCreate: Specifies that the operating system should open an existing file. If the file does not exist, it creates a new file with the specified name. Truncate: Opens an existing file, and once opened, the file is truncated to zero bytes. We can then write new data to the file, but the initial creation date of the file is retained. If the file does not exist, an exception is thrown.
FileAccess Members of the FileAccess enumeration include: Read, ReadWrite, and Write.

FileShare Enumeration Members:

Example

The following program demonstrates the usage of the FileStream class:

using System;
using System.IO;

namespace FileIOApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            FileStream F = new FileStream("test.dat", 
            FileMode.OpenOrCreate, FileAccess.ReadWrite);

            for (int i = 1; i <= 20; i++)
            {
                F.WriteByte((byte)i);
            }

            F.Position = 0;

            for (int i = 0; i <= 20; i++)
            {
                Console.Write(F.ReadByte() + " ");
            }
            F.Close();
            Console.ReadKey();
        }
    }
}

When the above code is compiled and executed, it produces the following result:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 -1

Advanced File Operations in C

The above example demonstrates simple file operations in C#. However, to fully utilize the power of C# System.IO classes, you need to know the commonly used properties and methods of these classes.

In the following sections, we will discuss these classes and the operations they perform. Click on the links to learn more about each topic:

Topic Description
Reading and Writing Text Files It involves reading and writing text files. The StreamReader and StreamWriter classes help in reading and writing text files.
Reading and Writing Binary Files It involves reading and writing binary files. The BinaryReader and BinaryWriter classes help in reading and writing binary files.
Operating on the Windows File System It allows C# programmers to browse and locate Windows files and directories.
❮ Csharp Regular Expressions Csharp Unsafe Codes ❯