C# FileMode and FileAccess Enums

Learn about FileStream class. How to open a file with given mode and then provide access to file in C#?
Submitted by IncludeHelp, on November 17, 2017 [Last updated : March 27, 2023]

C# FileMode Enum

Here, FileMode is an enum that contains following items.

  1. FileMode.Open
    This mode specifies that we can open an existing file.
  2. FileMode.OpenOrCreate
    This mode specifies that we can open an existing file. If file does not exist then it creates new file.
  3. FileMode.Create
    This mode specifies that we create a new file. If file already exists then it overwrites old file.
  4. FileMode.CreateNew
    This mode specifies that we create a new file. If file already exists then it thrown an exception.
  5. FileMode.Append
    This mode specifies that Open a file and seeks to the end of file. If file does not exist then it creates new file.
  6. FileMode.Truncate
    This mode specifies that open a existing file, then truncate that file.

Syntax

public enum FileMode

C# FileAccess Enum

Here, FileAccess is an enum that contains following items

  1. FileAccess.Read
    Provide read access of file.
  2. FileAccess.Write
    Provide write access of file.
  3. FileAccess.ReadWrite
    Provide read and write both access of file.

Syntax

public enum FileAccess

Example of FileMode and FileAccess Enums in C#

using System;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            byte b1 = 10;
            byte b2 = 0;

            FileStream f1;
            FileStream f2;

            f1 = new FileStream("abc.txt", FileMode.Create, FileAccess.Write);

            f1.WriteByte(b1);
            f1.Close();

            f2 = new FileStream("abc.txt", FileMode.Open, FileAccess.Read);
            
            b2 = (byte)f2.ReadByte();
            Console.WriteLine("Val : " + b2);
            f2.Close();
        }
    }
}

Output

Val : 10

Explanation

In above program, we need to remember, when we use "FileStream" class then we need to include System.IO namespace in the program.

C# FileStream Class Program »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.