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 customReverseString()
method, and then writes the reversed lines to a file named “output.txt” using aStreamWriter
. The following steps are performed:
- Define the input and output file paths as variables.
- Use
File.ReadAllLines()
to read the contents of the input file into a string array.- Use a
StreamWriter
to write the reversed lines to the output file.- Catch any exceptions that may occur during the process and handle them accordingly.