C# Example: Reading data from a file and writing it to another file using C# - Biz Tech

C# Example: Reading data from a file and writing it to another file using C#

Listen
 using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        string inputFilePath = "input.txt";
        string outputFilePath = "output.txt";

        try
        {
            string[] lines = File.ReadAllLines(inputFilePath);

            using (StreamWriter writer = new StreamWriter(outputFilePath))
            {
                foreach (string line in lines)
                {
                    string reversedLine = ReverseString(line);
                    writer.WriteLine(reversedLine);
                }
            }

            Console.WriteLine("Data written to output file.");
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("Input file not found.");
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }

    static string ReverseString(string input)
    {
        char[] charArray = input.ToCharArray();
        Array.Reverse(charArray);
        return new string(charArray);
    }
}

This example reads the contents of a file named “input.txt” using File.ReadAllLines(), reverses each line using a custom ReverseString() method, and then writes the reversed lines to a file named “output.txt” using a StreamWriter. The following steps are performed:

  1. Define the input and output file paths as variables.
  2. Use File.ReadAllLines() to read the contents of the input file into a string array.
  3. Use a StreamWriter to write the reversed lines to the output file.
  4. Catch any exceptions that may occur during the process and handle them accordingly.