0
0
C Sharp (C#)programming~10 mins

Writing text files in C Sharp (C#) - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
AFile.Write
BHello, world!
CWriteLine
D"Hello, world!"
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to put the text inside quotes.
Using a method name instead of the text string.
2fill in blank
medium

Complete 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'
AAppendAllText
BWriteAllText
CWriteLine
DWriteText
Attempts:
3 left
💡 Hint
Common Mistakes
Using WriteAllText which overwrites the file.
Using a non-existent method like WriteLine.
3fill in blank
hard

Fix 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'
Astring.Join("\n", lines)
Blines
Clines.ToString()
Dlines[0]
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the array directly which causes an error.
Using ToString() on the array which returns the type name.
4fill in blank
hard

Fill 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'
Atrue
Bfalse
CWriteLine
DWrite
Attempts:
3 left
💡 Hint
Common Mistakes
Using false for append which overwrites the file.
Using Write which does not add a newline.
5fill in blank
hard

Fill 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'
Afalse
Bline
CWriteLine
Dtrue
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.