C# File input and output

aFileIs a data collection stored on disk with a specified name and directory path. When a file is opened for reading and writing, it becomes aflow。

Fundamentally, a stream is a sequence of bytes transmitted through a communication path. There are two main streams:input streamandoutput stream。input streamUsed to read data from a file (read operations),output streamUsed to write data to a file (write operations).

C# I/O classes

The System.IO namespace has various classes for performing various file operations, such as creating and deleting files, reading or writing files, closing files, and so on.

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

I/O classDescription
BinaryReaderReads raw data from a binary stream.
BinaryWriterWrites raw data in binary format.
BufferedStreamTemporary storage for byte streams.
DirectoryHelps with directory structure operations.
DirectoryInfoUsed to perform operations on directories.
DriveInfoProvides information about drives.
FileHelps in processing files.
FileInfoUsed to perform operations on files.
FileStreamUsed for reading and writing at any position in a file.
MemoryStreamUsed for random access to data streams stored in memory.
PathPerforms operations on path information.
StreamReaderUsed to read characters from a byte stream.
StreamWriterUsed to write characters to a stream.
StringReaderUsed to read a string buffer.
StringWriterUsed to write a string buffer.

FileStream class

In the System.IO namespace,FileStreamThe class facilitates reading, writing, and closing of files. This class is derived from the abstract class Stream.

You need to create aFileStreamobject to create a new file, or open an existing file. CreatingFileStreamThe syntax of the object is as follows:

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

For example, create a FileStream objectFto read a file namedsample.txtFile:

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

FileModeThe enumeration defines various methods of opening files. The members of the FileMode enumeration are:

  • Append: Opens an existing file and places the cursor at the end of the file. If the file does not exist, it creates the file.
  • Create: Creates a new file. If the file already exists, it deletes the old file and then creates a new file.
  • 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 and opens it.
  • Truncate: Opens an existing file and truncates it to zero bytes size once opened. Then we can write entirely new data to the file, but the initial creation date of the file is preserved. If the file does not exist, an exception is thrown.
FileAccess

FileAccessThe members of the enumeration are:Read、ReadWriteandWrite。

FileShare

FileShareThe members of the enumeration are:

  • Inheritable: Allows the file handle to be inherited by child processes. Win32 does not directly support this functionality.
  • None: Declines sharing of the current file. Before the file is closed, any request to open the file (whether made by this process or another process) will fail.
  • Read: Allows subsequent opening of the file for reading. If this flag is not specified, any request to open the file for reading (made by this process or another process) will fail before the file is closed. However, even if this flag is specified, additional permissions may still be required to access the file.
  • ReadWrite: Allows subsequent opening of the file for reading or writing. If this flag is not specified, any request to open the file for reading or writing (made by this process or another process) will fail before the file is closed. However, even if this flag is specified, additional permissions may still be required to access the file.
  • Write: Allows subsequent opening of the file for writing. If this flag is not specified, any request to open the file for writing (made by this process or another process) will fail before the file is closed. However, even if this flag is specified, additional permissions may still be required to access the file.
  • Delete: Allows the file to be deleted subsequently.

Example

The following program demonstratesFileStreamClass usage:

Example

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 results:

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

C# Advanced File Operations

The above examples demonstrate simple file operations in C#. However, to fully utilize the powerful features of the 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. Please click the links to learn more about each part:

topicDescription
Reading and Writing Text FilesIt involves reading and writing text files.StreamReaderandStreamWriterThe class helps in completing the reading and writing of text files.
Reading and writing binary filesIt involves reading and writing binary files.BinaryReaderandBinaryWriterThe class facilitates reading and writing of binary files.
Windows file system operationsIt allows C# programmers to browse and locate Windows files and directories.
other extensions