File I/O (Input/Output) in C# allows you to read from and write to files on the filesystem. The System.IO namespace contains classes for working with files and directories. Below are detailed examples of common file I/O operations in C#.
1. File
- Description: Provides static methods for file operations.
- Notable Methods:
Create()
Copy()
Delete()
Exists()
Open()
ReadAllText()
WriteAllText()
2. FileInfo
- Description: Provides instance methods for file operations.
- Notable Methods:
CopyTo()
Delete()
Exists()
MoveTo()
Open()
OpenRead()
OpenText()
Refresh()
3. Directory
- Description: Provides static methods for directory operations.
- Notable Methods:
CreateDirectory()
Delete()
Exists()
GetFiles()
GetDirectories()
GetCurrentDirectory()
4. DirectoryInfo
- Description: Provides instance methods for directory operations.
- Notable Methods:
Create()
Delete()
GetFiles()
GetDirectories()
MoveTo()
Refresh()
5. FileStream
- Description: Provides a stream for file operations.
- Notable Methods:
Read()
Write()
Seek()
Flush()
Close()
SetLength()
6. StreamReader
- Description: Reads characters from a byte stream.
- Notable Methods:
Read()
ReadLine()
ReadToEnd()
Peek()
Close()
7. StreamWriter
- Description: Writes characters to a stream.
- Notable Methods:
Write()
WriteLine()
Flush()
Close()
Dispose()
8. BinaryReader
- Description: Reads primitive types as binary values.
- Notable Methods:
ReadInt32()
ReadString()
ReadBytes()
ReadBoolean()
Close()
9. BinaryWriter
- Description: Writes primitive types in binary format.
- Notable Methods:
Write()
Flush()
Close()
WriteInt32()
WriteString()
10. MemoryStream
- Description: Provides a stream that uses memory as its backing store.
- Notable Methods:
Read()
Write()
ToArray()
SetLength()
GetBuffer()
11. Path
- Description: Provides methods for processing file and directory paths.
- Notable Methods:
Combine()
GetFileName()
GetExtension()
GetDirectoryName()
ChangeExtension()
12. FileSystemWatcher
- Description: Watches for changes in the file system.
- Notable Methods:
Start()
Stop()
Dispose()
WaitForChanged()
13. TextReader
- Description: Base class for reading characters from a stream.
- Notable Methods:
Read()
ReadLine()
ReadToEnd()
Close()
Peek()
14. TextWriter
- Description: Base class for writing characters to a stream.
- Notable Methods:
Write()
WriteLine()
Flush()
Close()
Dispose()
1. Writing to a File
You can write text to a file using StreamWriter
, File.WriteAllText
, or File.AppendAllText
. Here’s an example using StreamWriter
.
Example: Writing to a File
csharp1using System; 2using System.IO; 3 4class Program 5{ 6 static void Main() 7 { 8 string filePath = "example.txt"; 9 10 // Using StreamWriter to write to a file 11 using (StreamWriter writer = new StreamWriter(filePath)) 12 { 13 writer.WriteLine("Hello, World!"); 14 writer.WriteLine("Welcome to C# File I/O."); 15 writer.WriteLine("This is a sample text file."); 16 } 17 18 Console.WriteLine($"Data written to {filePath}"); 19 } 20}
2. Reading from a File
To read text from a file, you can use StreamReader
, File.ReadAllText
, or File.ReadAllLines
. Here’s an example using StreamReader
.
Example: Reading from a File
csharp1using System; 2using System.IO; 3 4class Program 5{ 6 static void Main() 7 { 8 string filePath = "example.txt"; 9 10 // Using StreamReader to read from a file 11 using (StreamReader reader = new StreamReader(filePath)) 12 { 13 string line; 14 while ((line = reader.ReadLine()) != null) 15 { 16 Console.WriteLine(line); 17 } 18 } 19 } 20}
3. Checking if a File Exists
Before performing operations on a file, you may want to check if the file exists using File.Exists
.
Example: Checking if a File Exists
csharp1using System; 2using System.IO; 3 4class Program 5{ 6 static void Main() 7 { 8 string filePath = "example.txt"; 9 10 if (File.Exists(filePath)) 11 { 12 Console.WriteLine($"{filePath} exists."); 13 } 14 else 15 { 16 Console.WriteLine($"{filePath} does not exist."); 17 } 18 } 19}
4. Appending to a File
You can append text to an existing file using StreamWriter
with the append
parameter set to true
.
Example: Appending to a File
csharp1using System; 2using System.IO; 3 4class Program 5{ 6 static void Main() 7 { 8 string filePath = "example.txt"; 9 10 // Appending text to a file 11 using (StreamWriter writer = new StreamWriter(filePath, true)) 12 { 13 writer.WriteLine("This line is appended to the file."); 14 } 15 16 Console.WriteLine("Data appended to the file."); 17 } 18}
5. Deleting a File
You can delete a file using File.Delete
.
Example: Deleting a File
csharp1using System; 2using System.IO; 3 4class Program 5{ 6 static void Main() 7 { 8 string filePath = "example.txt"; 9 10 if (File.Exists(filePath)) 11 { 12 File.Delete(filePath); 13 Console.WriteLine($"{filePath} has been deleted."); 14 } 15 else 16 { 17 Console.WriteLine($"{filePath} does not exist."); 18 } 19 } 20}
6. Working with Directories
You can also create, delete, and check for directories using the Directory
class.
Example: Creating and Deleting a Directory
csharp1using System; 2using System.IO; 3 4class Program 5{ 6 static void Main() 7 { 8 string directoryPath = "exampleDir"; 9 10 // Create a directory 11 if (!Directory.Exists(directoryPath)) 12 { 13 Directory.CreateDirectory(directoryPath); 14 Console.WriteLine($"Directory {directoryPath} created."); 15 } 16 17 // Delete the directory 18 if (Directory.Exists(directoryPath)) 19 { 20 Directory.Delete(directoryPath); 21 Console.WriteLine($"Directory {directoryPath} deleted."); 22 } 23 } 24}
7. Copying and Moving Files
You can copy and move files using File.Copy
and File.Move
.
Example: Copying and Moving Files
csharp1using System; 2using System.IO; 3 4class Program 5{ 6 static void Main() 7 { 8 string sourceFile = "example.txt"; 9 string copyFile = "example_copy.txt"; 10 string moveFile = "example_moved.txt"; 11 12 // Copying a file 13 if (File.Exists(sourceFile)) 14 { 15 File.Copy(sourceFile, copyFile, true); // true to overwrite if exists 16 Console.WriteLine($"File copied to {copyFile}"); 17 } 18 19 // Moving a file 20 if (File.Exists(copyFile)) 21 { 22 File.Move(copyFile, moveFile); 23 Console