Consider the following C# code that writes text to a file and then reads it back. What will be printed on the console?
using System; using System.IO; class Program { static void Main() { string path = "testfile.txt"; File.WriteAllText(path, "Hello World!"); string content = File.ReadAllText(path); Console.WriteLine(content); } }
Think about what File.WriteAllText and File.ReadAllText do.
The code writes the string "Hello World!" to the file named "testfile.txt" and then reads it back. The console prints the content read, which is "Hello World!".
What will happen when running this C# code?
using System; using System.IO; class Program { static void Main() { string path = "nonexistent_dir/output.txt"; File.WriteAllText(path, "Data"); Console.WriteLine("Done"); } }
Does File.WriteAllText create missing directories automatically?
The method File.WriteAllText does not create directories. If the directory does not exist, it throws a DirectoryNotFoundException.
The following code throws an exception. Identify the cause.
using System; using System.IO; class Program { static void Main() { string path = "output.txt"; using (StreamWriter writer = new StreamWriter(path)) { writer.WriteLine("Line 1"); } writer.WriteLine("Line 2"); } }
Check where the writer variable is accessible.
The writer variable is declared inside the using block and disposed at the end of it. Trying to use it outside causes an ObjectDisposedException.
Which of the following C# methods appends text to a file instead of overwriting it?
Look for the method name that suggests adding to the end.
File.AppendAllText adds text to the end of the file without deleting existing content. File.WriteAllText overwrites the file.
Given the code below, what will be the content of log.txt after execution?
using System; using System.IO; class Program { static void Main() { string path = "log.txt"; File.WriteAllText(path, "Start\n"); using (StreamWriter sw = new StreamWriter(path, append: true)) { sw.WriteLine("Middle"); } File.WriteAllText(path, "End"); } }
Consider the order of file writes and whether content is overwritten.
The first WriteAllText writes "Start\n". Then StreamWriter appends "Middle\n". Finally, WriteAllText overwrites the entire file with "End". So the file only contains "End".