C# File I/O

Deep dive into file processing in C#.

File Processing

File processing in C# involves various operations such as reading from and writing to files, manipulating file contents, checking file attributes, and managing directories. Let's explore each of these aspects:

1. Reading from Files:

string[] lines = File.ReadAllLines("example.txt");
foreach (string line in lines)
{
    Console.WriteLine(line);
}

You can use the 'StreamReader' or 'File.ReadAllLines' method to read text files line by line or read all lines at once. For binary files, you can use 'FileStream' or 'BinaryReader'.

2. Writing to Files:

string[] lines = { "Line 1", "Line 2", "Line 3" };
File.WriteAllLines("example.txt", lines);

You can use the 'StreamWriter' or 'File.WriteAllText' method to write to text files, or 'FileStream' or 'BinaryWriter for binary files.

3. Appending to Files:

using (StreamWriter writer = new StreamWriter("example.txt", true))
{
    writer.WriteLine("Additional line");
}

To append text to an existing file, you can use 'StreamWriter' with the constructor that accepts a file path and a boolean indicating whether to append.

4. Manipulating File Contents:

string content = File.ReadAllText("example.txt");
content = content.Replace("old", "new");
File.WriteAllText("example.txt", content);

You can read the contents of a file into a string or byte array, manipulate them, and then write back to the file.

5. Checking File Attributes:

if (File.Exists("example.txt"))
{
    FileInfo fileInfo = new FileInfo("example.txt");
    Console.WriteLine($"Size: {fileInfo.Length} bytes");
    Console.WriteLine($"Created: {fileInfo.CreationTime}");
    Console.WriteLine($"Last Accessed: {fileInfo.LastAccessTime}");
    Console.WriteLine($"Last Written: {fileInfo.LastWriteTime}");
}

You can check various attributes of a file such as its existence, size, creation time, last access time, and last write time using methods in the 'File' or 'FileInfo' class.

6. Managing Directories:

Directory.CreateDirectory("NewFolder");
Directory.Move("NewFolder", "NewFolderRenamed");
string[] directories = Directory.GetDirectories("ParentDirectory");
foreach (string dir in directories)
{
    Console.WriteLine(dir);
}

ou can create, delete, move, and enumerate directories using methods in the 'Directory' or 'DirectoryInfo' class.

Remember: Handle exceptions appropriately, especially when dealing with file I/O operations as they can fail due to various reasons like insufficient permissions, disk full, etc.

Coding Example:

Let's create a simple C# console application that reads data from a text file, performs some manipulation on the data, and then writes the manipulated data back to another file. In this example, we'll read a list of names from one file, convert them to uppercase, and write the uppercase names to another file.

input.txt
txt (Text File) Copy Code
The text needs to be converted to upper case.
Before Execution: output.txt
txt (Text File) Copy Code

                                
                                Program.cs
                                
cs Copy Code
using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        // File paths
        string inputFile = "input.txt";
        string outputFile = "output.txt";

        try
        {
            // Read names from input file
            string[] names = File.ReadAllLines(inputFile);

            // Process names (convert to uppercase)
            for (int i = 0; i < names.Length; i++)
            {
                names[i] = names[i].ToUpper();
            }

            // Write processed names to output file
            File.WriteAllLines(outputFile, names);

            Console.WriteLine("Converted to uppercase successfully.");
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("Input file not found.");
        }
        catch (IOException ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An unexpected error occurred: {ex.Message}");
        }
    }
}
Output:
Converted to uppercase successfully.
After Execution: output.txt
txt (Text File) Copy Code
THE TEXT NEEDS TO BE CONVERTED TO UPPER CASE.

Make sure you have a file named 'input.txt' with some names in it in the same directory as the executable of this program. After running the program, it will convert each name to uppercase and write the modified names to 'output.txt'.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.