Skip to content

Commit cc34db9

Browse files
committed
Adding solution to Quiz 8
1 parent 7ff4d5c commit cc34db9

1 file changed

Lines changed: 42 additions & 0 deletions

File tree

source/solutions/io/files.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,50 @@ tags:
2323
- [x] Always call the `Close` method after being done reading from or writing into a file.
2424
- [ ] Never read from or write into a file inside a `try-catch` block.
2525

26+
#. The `StreamReader` class contains a method called…
27+
28+
- [ ] … `.Open`
29+
- [x] … `.Close`.
30+
- [x] … `.ReadLine`
31+
- [ ] … `.WriteLine`
32+
- [ ] … `.NextLine`
33+
34+
#. If a file is located at `~/upload/teaching/2026/spring/quiz8.md`, then…
35+
36+
- [x] … its extension is `md`.
37+
- [ ] … it is safe to assume that it can be accessed by all users.
38+
- [ ] … it will have the same path if transferred to a computer using Windows.
39+
- [x] … it is located in a folder called `spring`.
40+
2641
## Problems
2742

43+
#. Assume that `filePath` contains the path to a text file. Briefly explain what the following program would do, and how it could be made safer to execute.
44+
45+
```
46+
StreamWriter sw = new StreamWriter(filePath);
47+
sw.WriteLine("Hello World!!");
48+
```
49+
50+
<details><summary>Solution</summary>
51+
This program would
52+
53+
#. Create a file located at `filePath`,
54+
#. Store in the file "Hello World!!", followed by a new line.
55+
56+
This program is unsafe because:
57+
58+
#. It does not close the file properly,
59+
#. It can throw exceptions if e.g., `filePath` cannot be accessed by the program,
60+
#. It possibly overwrite the file located at `filePath`.
61+
62+
To solve those, it should be edited to:
63+
64+
#. Close the file using `sw.Close()`,
65+
#. Be wrapped inside a `try`…`catch` block,
66+
#. Either test first if the file exists, or use the `StreamWriter` constructor that appends to the file if it already exists.
67+
</details>
68+
69+
2870
#. Write a program that create a text file called `HelloWorld.txt` in its `bin/Debug` folder and store "Hello" followed by a name entered by the user in it.
2971

3072
<details><summary>Solution</summary>

0 commit comments

Comments
 (0)