C# Example: Reading a text file, manipulating its contents, and writing the modified contents back to the file - Biz Tech

C# Example: Reading a text file, manipulating its contents, and writing the modified contents back to the file

Listen
using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        string filePath = "example.txt";

        string[] lines = File.ReadAllLines(filePath);

        for (int i = 0; i < lines.Length; i++)
        {
            lines[i] = lines[i].ToUpper();
        }

        File.WriteAllLines(filePath, lines);

        Console.WriteLine("Modified file contents:");
        Console.WriteLine(string.Join(Environment.NewLine, lines));
    }
}
 

This example reads the contents of a text file into an array of strings, converts each string to uppercase, writes the modified contents back to the file, and outputs the modified contents to the console. The following steps are performed:

  1. Define a string variable filePath with the value “example.txt”.
  2. Use the File.ReadAllLines() method to read the contents of the file at filePath into an array of strings lines.
  3. Use a for loop to iterate over each element of lines and convert it to uppercase using the ToUpper() method.
  4. Use the File.WriteAllLines() method to write the modified contents of lines back to the file at filePath.
  5. Output the modified contents of lines to the console using Console.WriteLine().

Note that there are many other types of file operations you can perform, such as creating, copying, and deleting files, as well as working with other file formats such as binary files and XML files. This example is just one possible multi-step process for working with files.