FileAccess Enum

Specifies constants that define the values for read, write, or read/write access to a file.

Namespace: System.IO

Assembly: mscorlib (in mscorlib.dll)

Members

Member name Description
Read The file can be read.
Write The file can be written to.
ReadWrite The file can be read from and written to.

Remarks

The FileAccess enumeration is used to specify the access mode when opening a file. For example, you can open a file for reading only, writing only, or both reading and writing.

This enumeration is used by constructors of the FileStream class, and by the File.Open method.

Examples

The following code example demonstrates how to open a file for reading and writing using the FileAccess enumeration.

using System;
using System.IO;

public class Example
{
    public static void Main()
    {
        string filePath = "myFile.txt";
        try
        {
            // Create a file or open it if it exists for reading and writing.
            using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                // Write some data to the file
                byte[] dataToWrite = System.Text.Encoding.UTF8.GetBytes("Hello, .NET Framework!");
                fs.Write(dataToWrite, 0, dataToWrite.Length);
                fs.Flush(); // Ensure data is written to disk

                // Move the stream position to the beginning to read
                fs.Seek(0, SeekOrigin.Begin);

                // Read data from the file
                byte[] dataToRead = new byte[fs.Length];
                fs.Read(dataToRead, 0, dataToRead.Length);
                string content = System.Text.Encoding.UTF8.GetString(dataToRead);

                Console.WriteLine($"File content: {content}");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}

Requirements

Namespace: System.IO
Platform: Windows
.NET Framework Security: Code Access Security