Consider a file named example.txt containing the text Hello World. What will the following C# code output?
string content = System.IO.File.ReadAllText("example.txt"); Console.WriteLine(content);
File.ReadAllText reads the entire content of the file as a string.
The method File.ReadAllText reads all text from the file and returns it as a string. Since the file contains "Hello World", that is printed.
What will the following code print if the file missing.txt does not exist?
bool exists = System.IO.File.Exists("missing.txt"); Console.WriteLine(exists);
File.Exists returns a boolean indicating if the file is present.
If the file does not exist, File.Exists returns false without throwing an exception.
Given a file data.txt with these lines:
Line1 Line2 Line3
What will the following code print?
string[] lines = System.IO.File.ReadAllLines("data.txt"); Console.WriteLine(lines.Length);
File.ReadAllLines returns an array of lines from the file.
The file has 3 lines, so the array length is 3.
What exception will be thrown if you try to delete a file that is currently open and locked by another process?
System.IO.File.Delete("lockedfile.txt");
Deleting a locked file causes an IO error.
When a file is locked by another process, File.Delete throws an IOException indicating the file cannot be accessed.
Which static method of the File class will create a new file or overwrite an existing file with the given string content?
One method writes text and replaces existing content.
File.WriteAllText writes the string to the file, creating it if missing or overwriting if it exists. AppendAllText adds to the end, Create returns a stream, and OpenRead opens for reading only.