C# Tutoriallogin
C# Tutorial
author:php.cn  update time:2022-04-11 14:06:23

C# file input and output



A file is a collection of data stored on 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 passed over a communication path. There are two main streams: Input stream and Output stream. Input stream is used to read data from the file (read operation), Output stream is used to write data to the file (write operation).

C# I/O Classes

The System.IO namespace has various classes that are used to perform various file operations such as creating and deleting files, reading or writing Import files, close files, etc.

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

I/O ClassDescription
BinaryReaderRead raw data from a binary stream.
BinaryWriterWrite raw data in binary format.
BufferedStreamTemporary storage of byte stream.
Directory Helps in manipulating the directory structure.
DirectoryInfo is used to perform operations on the directory.
DriveInfo Provides drive information.
File Helps with working with files.
FileInfo is used to perform operations on files.
FileStream is used for reading and writing anywhere in the file.
MemoryStreamUsed for random access to a stream of data stored in memory.
PathPerform operations on path information.
StreamReader is used to read characters from a byte stream.
StreamWriter is used to write characters to a stream.
StringReader is used to read the string buffer.
StringWriter is used to write string buffer.

FileStream Class

The FileStream class in the System.IO namespace facilitates the reading, writing, and closing of files. This class is derived 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, create a FileStream object F to read a file named sample.txt:

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

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

  • Append: Open an existing file and place the cursor at the end of the file. If the file does not exist, create the file.

  • Create: Create a new file. If the file already exists, the old file is deleted and the new file is created.

  • CreateNew: Specifies that the operating system should create a new file. If the file already exists, an exception is thrown.

  • Open: Open 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, a new file is created with the specified name and opened.

  • Truncate: Open an existing file. Once the file is opened, it will be truncated to zero byte size. We can then write completely new data to the file but retain the original creation date of the file. If the file does not exist, an exception is thrown.

##FileAccess

The members of the enumeration are: Read, ReadWrite and Write.

FileShare

The members of the enumeration are:

  • Inheritable

    : Allow file handles to be inherited by child processes. Win32 does not directly support this feature.

  • None

    : Decline to share the current file. Any request to open the file (from this process or another process) will fail until the file is closed.

  • Read

    : Allows subsequent opening of the file for reading. If this flag is not specified, any request to open the file for reading (from this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions may be required to access the file.

  • ReadWrite: Allows the file to be subsequently opened for reading or writing. If this flag is not specified, any request to open the file for reading or writing (from this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions may 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 (from this process or another process) will fail until the file is closed. However, even if this flag is specified, additional permissions may be required to access the file.

  • Delete: Allows subsequent deletion of the file.

##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 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 example demonstrates simple file operations in C#. However, to take full advantage of the power of the C# System.IO classes, you need to know the properties and methods commonly used by these classes.

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

TopicDescriptionReading of text files WritingIt involves reading and writing text files. The Reading and writing of binary filesIt involves reading and writing of binary files. The Windows File System OperationsIt enables C# programmers to browse and locate Windows files and directories.
StreamReader and StreamWriter classes help in reading and writing text files.
BinaryReader and BinaryWriter classes help in reading and writing binary files.