System.IO.File Class
System.IO
Namespace: System.IO
Assembly: System.IO.dll
Summary
The System.IO.File
class provides static methods for the creation, copying, deletion, moving, and opening of files, and provides objects that enable you to read from and write to a file.
This class is designed to be used with file paths, which are strings representing the location of a file. It offers convenient methods for common file operations without needing to explicitly create or manage FileStream
objects in many cases.
System.IO.FileStream
directly.
Methods
AppendAllText
Method Overloads
Appends the specified string to the file, or creates the file, writing the specified string to it. If the file already exists, lines are appended to the end of the file.
public static void AppendAllText (string path, string contents);
public static void AppendAllText (string path, string contents, System.Text.Encoding encoding);
public static void AppendAllText (string path, ReadOnlySpan<char> contents, System.Text.Encoding encoding = null);
public static System.Threading.Tasks.Task AppendAllTextAsync (string path, string contents, System.Threading.CancellationToken cancellationToken = default);
public static System.Threading.Tasks.Task AppendAllTextAsync (string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default);
Parameters:
- path: The file path.
- contents: The string to append.
- encoding: The encoding to use for the file.
- cancellationToken: The token to monitor for cancellation requests. The default value is
System.Threading.CancellationToken.None
.
Copy
Method Overloads
Copies an existing file to a new location.
public static void Copy (string sourceFileName, string destFileName);
public static void Copy (string sourceFileName, string destFileName, bool overwrite);
Parameters:
- sourceFileName: The path to the file to copy.
- destFileName: The destination path to copy the current file to.
- overwrite:
true
to allow an existing file to be overwritten; otherwise,false
.
Delete
Method Overloads
Deletes the specified file.
public static void Delete (string path);
Parameters:
- path: The path of the file to delete.
Exists
Method Overloads
Determines whether the specified file exists.
public static bool Exists (string path);
Parameters:
- path: The file to check.
Returns:
true
if the caller has the required permissions and path
contains a file; otherwise, false
. This method also returns false
if path
is null
, an invalid path, or a zero-length string. If the caller does not have sufficient storage permissions to access the file, an UnauthorizedAccessException
is thrown. If path
specifies a directory, this method returns false
.
Move
Method Overloads
Moves a specified file to a new location, with options to handle file replacement.
public static void Move (string sourceFileName, string destFileName);
Parameters:
- sourceFileName: The path for the current file, which is to be moved.
- destFileName: The new path for the current file.
ReadAllBytes
Method Overloads
Opens a binary file, reads the contents of the file into a byte array, and then closes the file.
public static byte[] ReadAllBytes (string path);
public static System.Threading.Tasks.Task<byte[]> ReadAllBytesAsync (string path, System.Threading.CancellationToken cancellationToken = default);
Parameters:
- path: The file to read.
- cancellationToken: The token to monitor for cancellation requests. The default value is
System.Threading.CancellationToken.None
.
Returns:
A byte array containing the contents of the file.
ReadAllLines
Method Overloads
Opens a text file, reads all lines of the file into a string array, and then closes the file.
public static string[] ReadAllLines (string path);
public static string[] ReadAllLines (string path, System.Text.Encoding encoding);
public static System.Threading.Tasks.Task<string[]> ReadAllLinesAsync (string path, System.Threading.CancellationToken cancellationToken = default);
public static System.Threading.Tasks.Task<string[]> ReadAllLinesAsync (string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default);
Parameters:
- path: The file to read.
- encoding: The encoding to use for the file.
- cancellationToken: The token to monitor for cancellation requests. The default value is
System.Threading.CancellationToken.None
.
Returns:
A string array containing the lines of the file.
ReadAllText
Method Overloads
Opens a text file, reads all lines of the file into a string, and then closes the file.
public static string ReadAllText (string path);
public static string ReadAllText (string path, System.Text.Encoding encoding);
public static System.Threading.Tasks.Task<string> ReadAllTextAsync (string path, System.Threading.CancellationToken cancellationToken = default);
public static System.Threading.Tasks.Task<string> ReadAllTextAsync (string path, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default);
Parameters:
- path: The file to read.
- encoding: The encoding to use for the file.
- cancellationToken: The token to monitor for cancellation requests. The default value is
System.Threading.CancellationToken.None
.
Returns:
A string containing all lines of the file.
WriteAllBytes
Method Overloads
Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.
public static void WriteAllBytes (string path, byte[] bytes);
public static System.Threading.Tasks.Task WriteAllBytesAsync (string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = default);
Parameters:
- path: The file to write to.
- bytes: The byte array to write to the file.
- cancellationToken: The token to monitor for cancellation requests. The default value is
System.Threading.CancellationToken.None
.
WriteAllLines
Method Overloads
Creates a new file, writes a collection of strings to the file, and then closes the file. Each string corresponds to a line in the file.
public static void WriteAllLines (string path, string[] contents);
public static void WriteAllLines (string path, System.Collections.Generic.IEnumerable<string> contents);
public static void WriteAllLines (string path, string[] contents, System.Text.Encoding encoding);
public static void WriteAllLines (string path, System.Collections.Generic.IEnumerable<string> contents, System.Text.Encoding encoding);
public static System.Threading.Tasks.Task WriteAllLinesAsync (string path, string[] contents, System.Threading.CancellationToken cancellationToken = default);
public static System.Threading.Tasks.Task WriteAllLinesAsync (string path, System.Collections.Generic.IEnumerable<string> contents, System.Threading.CancellationToken cancellationToken = default);
public static System.Threading.Tasks.Task WriteAllLinesAsync (string path, string[] contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default);
public static System.Threading.Tasks.Task WriteAllLinesAsync (string path, System.Collections.Generic.IEnumerable<string> contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default);
Parameters:
- path: The file to write to.
- contents: The string array or collection to write to the file.
- encoding: The encoding to use for the file.
- cancellationToken: The token to monitor for cancellation requests. The default value is
System.Threading.CancellationToken.None
.
WriteAllText
Method Overloads
Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.
public static void WriteAllText (string path, string contents);
public static void WriteAllText (string path, string contents, System.Text.Encoding encoding);
public static System.Threading.Tasks.Task WriteAllTextAsync (string path, string contents, System.Threading.CancellationToken cancellationToken = default);
public static System.Threading.Tasks.Task WriteAllTextAsync (string path, string contents, System.Text.Encoding encoding, System.Threading.CancellationToken cancellationToken = default);
Parameters:
- path: The file to write to.
- contents: The string to write to the file.
- encoding: The encoding to use for the file.
- cancellationToken: The token to monitor for cancellation requests. The default value is
System.Threading.CancellationToken.None
.
Remarks
The File
class provides a convenient, high-level interface for file manipulation. It handles the underlying stream operations, buffering, and error handling for you, making common tasks simpler.
All methods in the File
class that perform file operations perform them synchronously by default, unless an asynchronous overload (e.g., `ReadAllBytesAsync`) is explicitly called.
Example
Writing and Reading a Text File
using System;
using System.IO;
public class FileExample
{
public static void Main(string[] args)
{
string filePath = "my_document.txt";
string content = "Hello, world!\nThis is a sample text file.";
try
{
// Write content to the file
File.WriteAllText(filePath, content);
Console.WriteLine($"Content written to {filePath}");
// Read content from the file
string readContent = File.ReadAllText(filePath);
Console.WriteLine($"\nContent read from {filePath}:");
Console.WriteLine(readContent);
// Append to the file
File.AppendAllText(filePath, "\nAppending a new line.");
Console.WriteLine($"\nContent appended to {filePath}");
// Read all lines
string[] lines = File.ReadAllLines(filePath);
Console.WriteLine("\nLines in the file:");
foreach (string line in lines)
{
Console.WriteLine($"- {line}");
}
// Check if file exists
if (File.Exists(filePath))
{
Console.WriteLine($"\nFile '{filePath}' exists.");
}
// Copy the file
string copyPath = "my_document_copy.txt";
File.Copy(filePath, copyPath, true);
Console.WriteLine($"File copied to '{copyPath}'.");
// Delete the original file
File.Delete(filePath);
Console.WriteLine($"Original file '{filePath}' deleted.");
// Move the copied file
string movePath = "moved_document.txt";
File.Move(copyPath, movePath);
Console.WriteLine($"File '{copyPath}' moved to '{movePath}'.");
}
catch (IOException ex)
{
Console.WriteLine($"An IO error occurred: {ex.Message}");
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine($"Permission error: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"An unexpected error occurred: {ex.Message}");
}
}
}