Consider this C# code that writes text to a file and then reads it back. What will it print?
using System; using System.IO; class Program { static void Main() { string path = "testfile.txt"; File.WriteAllText(path, "Hello File Operations!"); string content = File.ReadAllText(path); Console.WriteLine(content); } }
Think about what File.WriteAllText and File.ReadAllText do.
The code writes the string "Hello File Operations!" to a file named "testfile.txt" and then reads it back. The output is exactly the string written.
Why is it important to close a file after you finish working with it in C#?
Think about what happens if many files stay open at once.
Closing files releases system resources like memory and file handles. It also allows other programs to access the file without errors.
What error will this C# code produce when run?
using System; using System.IO; class Program { static void Main() { string content = File.ReadAllText("nonexistentfile.txt"); Console.WriteLine(content); } }
What happens if you try to read a file that does not exist?
The code tries to read a file that does not exist, so the system throws a FileNotFoundException.
Which of these C# code snippets correctly writes multiple lines to a file named "output.txt"?
Check the correct method name and parameters for writing multiple lines.
File.WriteAllLines takes a file path and a string array or IEnumerable<string> to write multiple lines. Other options use invalid method names or parameters.
Given this C# code, what will be the final content of "data.txt"?
using System; using System.IO; class Program { static void Main() { string path = "data.txt"; File.WriteAllText(path, "Start\n"); using (StreamWriter sw = File.AppendText(path)) { sw.WriteLine("Middle"); sw.WriteLine("End"); } string result = File.ReadAllText(path); Console.WriteLine(result); } }
Remember that WriteLine adds a newline after each line.
The code first writes "Start\n" to the file. Then it appends "Middle\n" and "End\n" using WriteLine. The final content has three lines, each ending with a newline.