System.IO.File

Namespace: System.IO Assembly: System.Runtime.dll Type: static class

Summary

The File class provides static methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects.

Members

Methods

SignatureDescription
static void AppendAllText(string path, string contents) Appends the specified string to the file, creating the file if it does not already exist.
static void Copy(string sourceFileName, string destFileName, bool overwrite = false) Copies an existing file to a new file, optionally overwriting the destination file if it already exists.
static FileStream Create(string path) Creates or overwrites a file in the specified path.
static bool Delete(string path) Deletes the specified file.
static bool Exists(string path) Determines whether the specified file exists.
static byte[] ReadAllBytes(string path) Opens a binary file, reads the contents of the file into a byte array, and then closes the file.
static string[] ReadAllLines(string path) Opens a text file, reads all lines of the file into a string array, and then closes the file.
static string ReadAllText(string path) Opens a text file, reads all characters in the file into a string, and then closes the file.
static void WriteAllBytes(string path, byte[] bytes) Creates a new file, writes the specified byte array to the file, and then closes the file.
static void WriteAllLines(string path, IEnumerable contents) Creates a new file, writes a collection of strings to the file, and then closes the file.
static void WriteAllText(string path, string contents) Creates a new file, writes the specified string to the file, and then closes the file.

Properties

PropertyDescription
static FileAttributes Attributes { get; set; } Gets or sets the attributes for the specified file.
static DateTime CreationTime { get; set; } Gets or sets the creation time of the specified file.
static DateTime LastAccessTime { get; set; } Gets or sets the last access time of the specified file.
static DateTime LastWriteTime { get; set; } Gets or sets the last write time of the specified file.

Examples

// Write a string to a file
File.WriteAllText(@"C:\temp\example.txt", "Hello, .NET!");

// Read the content back
string content = File.ReadAllText(@"C:\temp\example.txt");
Console.WriteLine(content);

// Append a line
File.AppendAllText(@"C:\temp\example.txt", "\nAppended line");

// Check existence
if (File.Exists(@"C:\temp\example.txt"))
{
    Console.WriteLine("File exists.");
}

// Delete the file
File.Delete(@"C:\temp\example.txt");