Home »
.Net »
C# Programs
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.
- FileMode.Open
This mode specifies that we can open an existing file.
- FileMode.OpenOrCreate
This mode specifies that we can open an existing file. If file does not exist then it creates new file.
- FileMode.Create
This mode specifies that we create a new file. If file already exists then it overwrites old file.
- FileMode.CreateNew
This mode specifies that we create a new file. If file already exists then it thrown an exception.
- 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.
- 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
- FileAccess.Read
Provide read access of file.
- FileAccess.Write
Provide write access of file.
- 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 »