C# File Handling
Objectives
- What is File Handling?
- Reading from and writing to files
- StreamReader and StreamWriter classes
- File and FileInfo classes
What is File Handling?
File Handling in C# involves performing operations on files, such as reading data from files, writing data to files, and manipulating file properties.
File Handling it enables your applications to interact with external files stored on disk, allowing you to store and retrieve data persistently.
Reading from and Writing to Files:
Csharp it provides various classes and methods for reading from and writing to files.
The most common approaches involve using the 'StreamReader' and 'StreamWriter' classes for reading and writing textual data, and the 'File' and 'FileInfo' classes for more advanced file operations.
StreamReader and StreamWriter Classes:
StreamReader:
The StreamReader class is used to read characters from a stream, typically a file.
It provides methods for reading data from a file line by line.
using (StreamReader reader = new StreamReader("example.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
StreamWriter:
The StreamWriter class is used to write characters to a stream, typically a file.
It provides methods for writing data to a file, such as writing strings or formatted data.
using (StreamWriter writer = new StreamWriter("example.txt"))
{
writer.WriteLine("Hello, world!");
writer.WriteLine("This is a line of text.");
}
File and FileInfo Classes:
File Class
This static class "File Class" contains static methods used in performing file operations like read/ write text or binary data, copy, move, delete and create files.
string[] lines = File.ReadAllLines("example.txt");
foreach (string line in lines)
{
Console.WriteLine(line);
}
FileInfo
‘FileInfo’ This Class it has instance methods as well as properties for dealing with files. It allows you to get information about a file such as size, its creation date and attributes.
FileInfo fileInfo = new FileInfo("example.txt");
Console.WriteLine("File Name: " + fileInfo.Name);
Console.WriteLine("File Size: " + fileInfo.Length);
Console.WriteLine("Creation Date: " + fileInfo.CreationTime);