Skip to content
read/write to a file

Code Display

using System; using System.IO; class Program { static void Main() { string filePath = @"C:\test\real.txt"; try { // Check if the file exists, create it if it doesn't if (!File.Exists(filePath)) { File.WriteAllText(filePath, "0 1 2 3 4 5 6 7 8 9"); // Sample content Console.WriteLine("File created at: " + filePath); } // Read the file string content = File.ReadAllText(filePath); // Extract the first four numbers string[] numbers = content.Split(' ', StringSplitOptions.RemoveEmptyEntries); int sum = 0; int count = 0; foreach (string number in numbers) { if (count >= 4) break; if (int.TryParse(number, out int parsedNumber)) { sum += parsedNumber; count++; } } // Append the sum as a new line to the file File.AppendAllText(filePath, Environment.NewLine + sum.ToString()); Console.WriteLine("Sum of the first four numbers added to the file successfully."); } catch (IOException e) { Console.WriteLine("An error occurred while reading or writing the file:"); Console.WriteLine(e.Message); } catch (Exception ex) { Console.WriteLine("An unexpected error occurred:"); Console.WriteLine(ex.Message); } } }