Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to write a line of text to a file.
C Sharp (C#)
using System.IO; File.WriteAllText("example.txt", [1]);
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to put the text inside quotes.
Using a method name instead of the text string.
✗ Incorrect
The WriteAllText method requires a string as the second argument, so the text must be in quotes.
2fill in blank
mediumComplete the code to append a line to an existing file.
C Sharp (C#)
using System.IO; File.[1]("example.txt", "New line");
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using WriteAllText which overwrites the file.
Using a non-existent method like WriteLine.
✗ Incorrect
AppendAllText adds text to the end of the file without overwriting it.
3fill in blank
hardFix the error in the code to write multiple lines to a file.
C Sharp (C#)
using System.IO;
string[] lines = {"First line", "Second line"};
File.WriteAllText("example.txt", [1]); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the array directly which causes an error.
Using ToString() on the array which returns the type name.
✗ Incorrect
WriteAllText expects a single string, so we join the array elements with newlines.
4fill in blank
hardFill both blanks to write lines to a file using a StreamWriter.
C Sharp (C#)
using System.IO; using (StreamWriter writer = new StreamWriter("example.txt", [1])) { writer.[2]("Hello"); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using false for append which overwrites the file.
Using Write which does not add a newline.
✗ Incorrect
The first blank is true to append to the file, and WriteLine writes a line with a newline.
5fill in blank
hardFill all three blanks to write multiple lines using StreamWriter in a loop.
C Sharp (C#)
using System.IO;
string[] lines = {"One", "Two", "Three"};
using (StreamWriter writer = new StreamWriter("example.txt", [1]))
{
foreach (string [2] in lines)
{
writer.[3]([2]);
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Setting append to false which erases the file.
Using an undefined variable name in the loop.
Using Write instead of WriteLine.
✗ Incorrect
We append to the file (true), use 'line' as the loop variable, and WriteLine to write each line.