using System; using System.IO; class Program { static void Main(string[] args) { string message = "Hello, World!"; string filePath = @"C:\example.txt"; // Create a new StreamWriter object to write to the file using (StreamWriter writer = new StreamWriter(filePath)) { // Write the message to the file writer.WriteLine(message); // Close the stream writer.Close(); } } }
using System; using System.IO; class Program { static void Main(string[] args) { try { string message = "Hello, World!"; string filePath = @"C:\example.txt"; // Create a new StreamWriter object to write to the file StreamWriter writer = new StreamWriter(filePath); // Write the message to the file writer.WriteLine(message); // Force a system-level flush of the buffer to write changes to disk writer.Flush(); // Close the stream writer.Close(); } catch (Exception ex) { // Handle any exceptions that may occur Console.WriteLine("Error: " + ex.Message); } } }This example is similar to Example #1, except that it includes a call to the `Flush()` method before calling the `Close()` method. The `Flush()` method ensures that any data still in the buffer is written to the file before the stream is closed. Package/Library: System.IO.