Working with files is a common task in software development, and C# provides a rich set of classes and methods to handle file operations efficiently and safely. This detailed guide covers everything from the basics of file I/O to advanced techniques, including reading, writing, manipulating files and directories, error handling, asynchronous operations, and best practices.
File handling refers to the process of reading data from and writing data to files stored on disk or other persistent storage. C# provides the System.IO namespace, which contains essential classes like File, FileInfo, Directory, DirectoryInfo, Stream, StreamReader, StreamWriter, FileStream, and others for working with files and directories.
The File class provides static methods for file operations (like create, delete, copy, move, read, write). FileInfo is an instance-based class offering similar functionality with additional file metadata.
Used to manipulate directories and their contents.
Provides a stream for reading and writing bytes to files. Used for more controlled file operations.
Specialized for reading and writing text files conveniently.
Helps in manipulating strings representing file paths safely and platform-independently.
There are multiple ways to create and write to files in C#:
string path = @"C:\temp\example.txt"; string content = "Hello, World!"; File.WriteAllText(path, content);
This method creates the file if it doesnβt exist or overwrites it if it does.
using (StreamWriter writer = new StreamWriter(path))
{
writer.WriteLine("First line");
writer.WriteLine("Second line");
}
StreamWriter is useful for writing lines and appending content.
string text = File.ReadAllText(path); Console.WriteLine(text);
using (StreamReader reader = new StreamReader(path))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
if (File.Exists(path))
{
Console.WriteLine("File exists.");
}
else
{
Console.WriteLine("File does not exist.");
}
FileInfo fileInfo = new FileInfo(path);
Console.WriteLine($"File Size: {fileInfo.Length} bytes");
Console.WriteLine($"Created On: {fileInfo.CreationTime}");
Console.WriteLine($"Last Modified: {fileInfo.LastWriteTime}");
if (File.Exists(path))
{
File.Delete(path);
Console.WriteLine("File deleted.");
}
string destPath = @"C:\temp\example_copy.txt"; File.Copy(path, destPath, overwrite: true);
string newPath = @"C:\temp\example_renamed.txt"; File.Move(path, newPath);
string dirPath = @"C:\temp\myfolder"; Directory.CreateDirectory(dirPath);
if (Directory.Exists(dirPath))
{
Console.WriteLine("Directory exists.");
}
string[] files = Directory.GetFiles(dirPath);
foreach (string file in files)
{
Console.WriteLine(file);
}
if (Directory.Exists(dirPath))
{
Directory.Delete(dirPath, recursive: true);
}
FileStream gives you control over how to read and write bytes, useful for binary files or when performance and buffering options matter.
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
// Work with the stream here
}
byte[] data = new byte[] { 1, 2, 3, 4, 5 };
using (FileStream fs = new FileStream(path, FileMode.Create))
{
fs.Write(data, 0, data.Length);
}
byte[] buffer = new byte[1024];
using (FileStream fs = new FileStream(path, FileMode.Open))
{
int bytesRead = fs.Read(buffer, 0, buffer.Length);
Console.WriteLine($"Read {bytesRead} bytes.");
}
The FileMode and FileAccess enums define how files are opened:
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
// read and write code
}
File operations can fail due to various reasons like missing permissions, files in use, path errors, or disk issues. Always use exception handling.
try
{
string text = File.ReadAllText(path);
Console.WriteLine(text);
}
catch (FileNotFoundException ex)
{
Console.WriteLine("File not found: " + ex.Message);
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine("Access denied: " + ex.Message);
}
catch (IOException ex)
{
Console.WriteLine("I/O error: " + ex.Message);
}
C# provides ways to create and manage temporary files.
string tempFile = Path.GetTempFileName();
Console.WriteLine("Temp file created at: " + tempFile);
File.Delete(tempFile);
Modern applications often require non-blocking file I/O for better performance and responsiveness. C# supports asynchronous file operations with methods ending in Async.
using System.Threading.Tasks;
async Task ReadFileAsync(string filePath)
{
using (StreamReader reader = new StreamReader(filePath))
{
string content = await reader.ReadToEndAsync();
Console.WriteLine(content);
}
}
async Task WriteFileAsync(string filePath, string content)
{
using (StreamWriter writer = new StreamWriter(filePath))
{
await writer.WriteAsync(content);
}
}
When reading or writing text files, encoding is important. The default is UTF-8, but you can specify other encodings.
using (StreamWriter writer = new StreamWriter(path, false, System.Text.Encoding.UTF8))
{
writer.WriteLine("Text with UTF-8 encoding");
}
The FileSystemWatcher class lets you monitor changes in files or directories.
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"C:\temp";
watcher.Filter = "*.txt";
watcher.Changed += (s, e) => Console.WriteLine($"File changed: {e.FullPath}");
watcher.EnableRaisingEvents = true;
Working with files in C# involves understanding the classes in the System.IO namespace, how to read, write, copy, move, and delete files safely, how to handle exceptions, and how to implement asynchronous operations. Proper use of these techniques helps build robust, maintainable applications that interact with the file system effectively.
C# is primarily used on the Windows .NET framework, although it can be applied to an open source platform. This highly versatile programming language is an object-oriented programming language (OOP) and comparably new to the game, yet a reliable crowd pleaser.
The C# language is also easy to learn because by learning a small subset of the language you can immediately start to write useful code. More advanced features can be learnt as you become more proficient, but you are not forced to learn them to get up and running. C# is very good at encapsulating complexity.
The decision to opt for C# or Node. js largely hinges on the specific requirements of your project. If you're developing a CPU-intensive, enterprise-level application where stability and comprehensive tooling are crucial, C# might be your best bet.
C# is part of .NET, a free and open source development platform for building apps that run on Windows, macOS, Linux, iOS, and Android. There's an active community answering questions, producing samples, writing tutorials, authoring books, and more.
Copyrights © 2024 letsupdateskills All rights reserved