| LINQ in C# | Exception Handling and Logging in C# | |
📂 File I/O in C# |
In C#, File I/O (Input/Output) refers to the process of reading from and writing to files, which is handled by the System.IO namespace. C# represents a file as a stream of bytes, and the System.IO classes provide different ways to interact with these streams.
When you open a file, you specify a FileMode from the System.IO enumeration to control how the operating system handles the file.
| FileMode Member | Description |
|---|---|
| Create | Creates a new file. Overwrites if it exists. |
| CreateNew | Creates a new file. Throws an exception if it exists. |
| Open | Opens an existing file. |
| OpenOrCreate | Opens an existing file or creates a new one if it doesn’t exist. |
| Append | Opens a file and seeks to the end. Creates the file if it doesn’t exist. |
| Truncate | Opens an existing file and sets its size to zero. |
File I/O (Input/Output) in C# is handled using the System.IO namespace. It allows you to create, read, write, append, and manipulate files and directories efficiently.
using System.IO;
File.WriteAllText("example.txt", "Hello, Shivshanker!");
string content = File.ReadAllText("example.txt");
Console.WriteLine(content);
File.AppendAllText("example.txt", "\nWelcome to File I/O in C#.");
string text = File.ReadAllText("example.txt");
text = text.Replace("Shivshanker", "Developer");
File.WriteAllText("example.txt", text);
string file1 = File.ReadAllText("file1.txt");
string file2 = File.ReadAllText("file2.txt");
File.WriteAllText("merged.txt", file1 + "\n" + file2);
File.WriteAllText writes a string to a new file, overwriting existing content.
using System;
using System.IO;
class FileOperations
{
static void Main()
{
string path = "example.txt";
string content = "This is the first line.\nThis is the second line.";
try
{
File.WriteAllText(path, content);
Console.WriteLine("File created and written successfully.");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
File.ReadAllText reads the entire content of a text file into a string.
using System;
using System.IO;
class FileOperations
{
static void Main()
{
string path = "example.txt";
try
{
if (File.Exists(path))
{
string content = File.ReadAllText(path);
Console.WriteLine("File content:");
Console.WriteLine(content);
}
else
{
Console.WriteLine("File not found.");
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
File.AppendAllText appends a string to a file, creating it if it doesn’t exist.
using System;
using System.IO;
class FileOperations
{
static void Main()
{
string path = "example.txt";
string contentToAppend = "\nThis is a new appended line.";
try
{
File.AppendAllText(path, contentToAppend);
Console.WriteLine("Content appended to file successfully.");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
Finding and replacing text often involves reading the file into memory, modifying the string, and writing it back.
using System;
using System.IO;
class FileOperations
{
static void Main()
{
string path = "example.txt";
try
{
if (File.Exists(path))
{
string content = File.ReadAllText(path);
content = content.Replace("second line", "replaced line");
File.WriteAllText(path, content);
Console.WriteLine("Content replaced successfully.");
}
else
{
Console.WriteLine("File not found.");
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
Merging files can be done by reading content from source files and writing it to a destination file using File.AppendAllLines to merge line by line.
using System;
using System.IO;
class FileOperations
{
static void Main()
{
string file1Path = "file1.txt";
string file2Path = "file2.txt";
string mergedFilePath = "merged.txt";
// Create example files
File.WriteAllText(file1Path, "Content from File 1.");
File.WriteAllText(file2Path, "Content from File 2.");
try
{
// Read all lines from the source files
string[] file1Content = File.ReadAllLines(file1Path);
string[] file2Content = File.ReadAllLines(file2Path);
// Merge the content into the new file
File.WriteAllLines(mergedFilePath, file1Content);
File.AppendAllLines(mergedFilePath, file2Content);
Console.WriteLine("Files merged successfully.");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
This example demonstrates how to find and replace specific text only on the lines where it occurs. It is memory-efficient, as it only holds one line in memory at a time.
StreamReader.using System;
using System.IO;
public class Program
{
public static void Main()
{
string inputPath = "input.txt";
string outputPath = "output.tmp"; // Temporary file
string findText = "old text";
string replaceText = "new text";
// Create a dummy input file for demonstration
File.WriteAllText(inputPath, "This line has old text that should be replaced.\n" +
"This line should remain unchanged.\n" +
"Another line with old text to be replaced.");
try
{
using (var reader = new StreamReader(inputPath))
using (var writer = new StreamWriter(outputPath))
{
string? line;
while ((line = reader.ReadLine()) != null)
{
if (line.Contains(findText))
{
// Replace the content within the current line only
string modifiedLine = line.Replace(findText, replaceText);
writer.WriteLine(modifiedLine);
}
else
{
// Write the original line unchanged
writer.WriteLine(line);
}
}
}
// Replace the original file with the new one
File.Delete(inputPath);
File.Move(outputPath, inputPath);
Console.WriteLine("File processing complete. Check input.txt for the changes.");
// Display the final content of the file
Console.WriteLine("\n--- Final file content ---");
Console.WriteLine(File.ReadAllText(inputPath));
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
}
System.IO namespace provides powerful classes for file manipulation.FileMode to control how files are opened or created.File.ReadAllText, File.WriteAllText, and File.AppendAllText for simple text operations.using blocks for StreamReader/StreamWriter to ensure proper disposal.File.Exists() before reading or deleting.try-catch to avoid crashes.Path.Combine() for cross-platform file paths.File I/O in C# is a powerful tool for managing data on disk. Whether you're creating logs, reading configs, or merging reports, mastering these operations will make your applications more robust and versatile.
| LINQ in C# | Exception Handling and Logging in C# | |