Namespace: System.IO
Specifies how the operating system should open a file.
Specifies that data will be written to the end of the file. If the file does not exist, a new file is created. This is equivalent to the O_APPEND
C run-time function.
If the file exists, the position for writing is set to the end of the file, regardless of the current position of the stream. If the file does not exist, this enumeration value is effectively the same as Create
.
Specifies that the operating system should create a new file. If the file already exists, it will be overwritten.
If the file already exists and is empty, it is overwritten. If the file already exists and contains data, it is overwritten. If the file does not exist, a new file is created.
Specifies that an existing file should be opened.
If the file does not exist, an IOException
is thrown.
Specifies that if the file exists, it should be opened; otherwise, a new file should be created.
If the file exists, it is opened. If the file does not exist, a new file is created.
Specifies that an existing file should be opened and its contents cleared. If the file does not exist, an IOException
is thrown.
If the file exists, it is opened and truncated. If the file does not exist, an IOException
is thrown.
Specifies that an existing file should be opened and the file is to be reopened. This is used for opening the same file multiple times.
This enumeration value is not commonly used. Its purpose is to allow a file to be opened more than once.
The FileMode
enumeration is used in conjunction with methods such as File.Open
, FileStream
, and Directory.CreateDirectory
to specify how a file or directory should be handled.
using System;
using System.IO;
public class Example
{
public static void Main()
{
string path = @"c:\temp\MyFile.txt";
// Create a new file, or overwrite an existing one
using (FileStream fs = new FileStream(path, FileMode.Create))
{
// Write data to the file
Byte[] info = new Byte[1024];
fs.Write(info, 0, info.Length);
}
// Open an existing file and append data to it
using (FileStream fs = new FileStream(path, FileMode.Append))
{
Byte[] info = new Byte[1024];
fs.Write(info, 0, info.Length);
}
// Open an existing file or create it if it doesn't exist
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
{
// Operations on the file
}
// Open an existing file, throwing an exception if it doesn't exist
try
{
using (FileStream fs = new FileStream(path, FileMode.Open))
{
// Operations on the file
}
}
catch (FileNotFoundException)
{
Console.WriteLine("File not found.");
}
// Truncate an existing file (clear its contents)
using (FileStream fs = new FileStream(path, FileMode.Truncate))
{
// The file is now empty
}
}
}