|
23 | 23 | - [x] Always call the `Close` method after being done reading from or writing into a file. |
24 | 24 | - [ ] Never read from or write into a file inside a `try-catch` block. |
25 | 25 |
|
| 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 | + |
26 | 41 | ## Problems |
27 | 42 |
|
| 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 | + |
28 | 70 | #. 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. |
29 | 71 |
|
30 | 72 | <details><summary>Solution</summary> |
|
0 commit comments