C# - Files
Handling files in C# involves reading from, writing to, and manipulating files on disk. The .NET Framework and .NET Core provide a range of classes and methods for file operations, primarily within the System.IO
namespace. Here’s a comprehensive guide to working with files in C#:
1. File Basics
The System.IO
namespace provides classes for file operations:
File
– Provides static methods for creating, copying, deleting, moving, and opening files.FileInfo
– Provides instance methods for file operations and properties to get file information.StreamReader
andStreamWriter
– Used for reading from and writing to files.FileStream
– Provides a stream for file operations, allowing more granular control.
2. Reading Files
Using StreamReader
StreamReader
is used to read text from files.
Example:
csharpusing System;
using System.IO;
class Program
{
static void Main()
{
string path = "example.txt";
// Using StreamReader to read the entire file
using (StreamReader reader = new StreamReader(path))
{
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
}
}
Reading Lines
To read a file line by line, you can use the ReadLine
method.
csharpusing System;
using System.IO;
class Program
{
static void Main()
{
string path = "example.txt";
using (StreamReader reader = new StreamReader(path))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
3. Writing Files
Using StreamWriter
StreamWriter
is used to write text to files.
Example:
csharpusing System;
using System.IO;
class Program
{
static void Main()
{
string path = "example.txt";
// Using StreamWriter to write text to a file
using (StreamWriter writer = new StreamWriter(path))
{
writer.WriteLine("Hello, World!");
writer.WriteLine("This is a new line.");
}
}
}
Appending Text
To append text to an existing file, use the File.AppendText
method.
csharpusing System;
using System.IO;
class Program
{
static void Main()
{
string path = "example.txt";
using (StreamWriter writer = File.AppendText(path))
{
writer.WriteLine("This line is appended.");
}
}
}
4. File Operations
File Creation and Deletion
You can create and delete files using the File
class.
csharpusing System;
using System.IO;
class Program
{
static void Main()
{
string path = "example.txt";
// Create a new file
if (!File.Exists(path))
{
File.Create(path).Dispose(); // Dispose to close the file handle
}
// Delete the file
if (File.Exists(path))
{
File.Delete(path);
}
}
}
File Copying and Moving
Copy and move files using the File
class methods.
csharpusing System;
using System.IO;
class Program
{
static void Main()
{
string sourcePath = "source.txt";
string destinationPath = "destination.txt";
// Copy the file
if (File.Exists(sourcePath))
{
File.Copy(sourcePath, destinationPath, true); // Overwrite if exists
}
// Move the file
if (File.Exists(destinationPath))
{
File.Move(destinationPath, "newDestination.txt");
}
}
}
5. File Information
To get information about a file, use the FileInfo
class.
Example:
csharpusing System;
using System.IO;
class Program
{
static void Main()
{
string path = "example.txt";
FileInfo fileInfo = new FileInfo(path);
if (fileInfo.Exists)
{
Console.WriteLine($"File Name: {fileInfo.Name}");
Console.WriteLine($"File Size: {fileInfo.Length} bytes");
Console.WriteLine($"Creation Time: {fileInfo.CreationTime}");
Console.WriteLine($"Last Access Time: {fileInfo.LastAccessTime}");
}
}
}
6. Working with Directories
Creating and Deleting Directories
Use the Directory
class to manage directories.
csharpusing System;
using System.IO;
class Program
{
static void Main()
{
string dirPath = "exampleDir";
// Create a new directory
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
// Delete the directory
if (Directory.Exists(dirPath))
{
Directory.Delete(dirPath, true); // true to delete recursively
}
}
}
Listing Files and Directories
List files and directories using Directory
methods.
csharpusing System;
using System.IO;
class Program
{
static void Main()
{
string dirPath = "exampleDir";
if (Directory.Exists(dirPath))
{
// List files
string[] files = Directory.GetFiles(dirPath);
foreach (string file in files)
{
Console.WriteLine(file);
}
// List directories
string[] directories = Directory.GetDirectories(dirPath);
foreach (string dir in directories)
{
Console.WriteLine(dir);
}
}
}
}
7. Handling Exceptions
File operations can throw exceptions, such as FileNotFoundException
, IOException
, and UnauthorizedAccessException
. Use try-catch blocks to handle these exceptions.
Example:
csharpusing System;
using System.IO;
class Program
{
static void Main()
{
string path = "example.txt";
try
{
using (StreamReader reader = new StreamReader(path))
{
string content = reader.ReadToEnd();
Console.WriteLine(content);
}
}
catch (FileNotFoundException ex)
{
Console.WriteLine("File not found: " + ex.Message);
}
catch (IOException ex)
{
Console.WriteLine("I/O error: " + ex.Message);
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine("Access denied: " + ex.Message);
}
}
}
8. Asynchronous File Operations
For I/O-bound operations, consider using asynchronous methods to improve performance and responsiveness.
Example:
csharpusing System;
using System.IO;
using System.Threading.Tasks;
class Program
{
static async Task Main()
{
string path = "example.txt";
// Asynchronous file writing
using (StreamWriter writer = new StreamWriter(path))
{
await writer.WriteLineAsync("Hello, asynchronous world!");
}
// Asynchronous file reading
using (StreamReader reader = new StreamReader(path))
{
string content = await reader.ReadToEndAsync();
Console.WriteLine(content);
}
}
}
Summary
Handling files in C# involves a variety of operations, including reading, writing, copying, moving, and deleting files, as well as managing directories. The System.IO
namespace provides the necessary classes and methods to perform these operations. Understanding how to work with files effectively can help you manage data persistence and file-related tasks in your C# applications.