Files and Text

9. Files and Text#

An order-import program must find its input, close every file it opens, and decide whether each line of text is usable before it updates a sales total. This chapter shows you how to write and read text files safely, give each program a folder it owns, make a program safe to run twice, and turn raw lines into validated business records. The text-processing section also applies security cases: masking personal data, treating input as untrusted, and logging rejections without leaking secrets. Regular expressions are a supporting reading.

  • Streams and files: StreamWriter and StreamReader move text between a program and a file, and using guarantees the file is closed.

  • Paths and workspaces: Path.Combine and an owned workspace folder keep a program’s files where it expects them.

  • Repeatable runs: Overwrite and append policies, temporary files, and missing-versus-empty checks let a program run twice without damage.

  • Structured records: Delimited lines such as CSV are split into fields, validated once by a reusable parser, and rejected with reasons.

  • Safe output: Masking, redaction, and minimal logs show no more personal data than the reader needs.

Chapter Video

Read and Write files in 10 minutes | C# (9:25) by tutorialsEU.

Hosted on YouTube; property of its original creator, embedded here for educational reference only.

Learning Objectives

By the end of this chapter, you will be able to:

  1. Write and read text files with StreamWriter and StreamReader inside using blocks, read line by line until ReadLine returns null, and explain why an unclosed writer can lose buffered output.

  2. Build file paths with Path.Combine inside a workspace folder your program owns, and distinguish absolute paths, relative paths, and the current directory.

  3. Use the File convenience methods (ReadAllLines, ReadLines, WriteAllLines, AppendAllText, and Exists), choose overwrite or append for a stated business policy, and name the encoding used to exchange text.

  4. Catch expected file errors such as FileNotFoundException, DirectoryNotFoundException, IOException, and UnauthorizedAccessException, and treat a missing file differently from an empty one.

  5. Make a program safe to run twice by writing complete output to a temporary file before replacing the result, and inspect folders with Directory and FileInfo.

  6. Split delimited lines into fields, validate field counts and values with one reusable TryParse parser that uses CultureInfo.InvariantCulture, and reject malformed lines with reasons while processing continues.

  7. Total records by key from a sales file into a dictionary, split a file into blank-line paragraphs, and load a lookup table with stated case and duplicate policies.

  8. Build reports with StringBuilder, mask or redact personal data, validate untrusted input against an allow-list, and write a rejection log that contains no secrets.

Supporting-reading outcome: read a regular expression as a description of accepted text, check for and extract matches, pull fields out with capture groups, and decide when string methods are the simpler tool.

Chapter Flow

Suggested three-meeting pace (115 minutes): read the relevant explanations and predict the selected example before class.

Meeting

Minutes

Guided focus

1

35

9.1: writing and reading with streams, using blocks, paths, the File convenience methods, and catching file errors.

2

40

9.2: owned workspace folders, append versus overwrite, safe repeated runs, totals by key from a sales file, and paragraphs and lookup tables.

3

40

9.3: splitting and validating fields with one parser, building text, processing a file of records, masking, and untrusted input.

Class uses selected traces, runs, and checks. Use the remaining worked examples for practice and reference. Supporting readings are selected separately; lab and homework follow the core lessons.

Glossary

#

Term

Explanation

1

Persistent data

Data that outlives the program run that created it, such as text saved in a file.

2

File

Named data stored outside a running program.

3

Text file

A file whose contents are characters organized as lines.

4

Line

A sequence of text ending at a line break.

5

Stream

A flow of data read from or written to a source, one piece at a time.

6

Buffer

Memory where a writer collects text before sending it to the file.

7

Flush

Sending buffered text to the file; closing a writer flushes it.

8

using statement

A block that closes a stream when control leaves it, even when an exception is thrown.

9

using declaration

A using written on a variable declaration, which closes the stream at the end of the enclosing block.

10

Path

A string that identifies a file or folder location.

11

Absolute path

A path that starts from the root of a drive or file system.

12

Relative path

A path interpreted from the current directory.

13

Current directory

The folder a program uses to resolve relative paths, also called the working directory.

14

Verbatim string

A string literal written with @ in which a backslash is an ordinary character.

15

Workspace folder

A folder a program creates and owns, so its files cannot collide with anyone else’s.

16

Encoding

Rules for representing text as bytes and decoding bytes back into text.

17

UTF-8

A Unicode encoding using a variable number of bytes per character.

18

Overwrite

Replace existing contents when writing a file.

19

Append

Add new data to the end of an existing file.

20

Partial output

An incomplete file left behind when a program fails partway through writing.

21

Temporary file

A file written first and moved into place only after the output is complete.

22

Repeatable run

A program run that produces the same result when repeated, without duplicating or corrupting output.

23

Lookup table

A dictionary loaded from a file that maps a key to a value, such as a product code to a response.

24

Paragraph

A group of lines separated from the next group by a blank line.

25

Record

One line of structured data, such as one order in a sales export.

26

Field

One value inside a record.

27

Delimiter

A character used to separate fields in text data.

28

CSV

Comma-separated values, a text format with one record per line and fields separated by commas.

29

Header row

A first line that names the fields rather than holding data.

30

Token

One piece of text produced by splitting a line.

31

Trim

Remove extra whitespace from the beginning or end of text.

32

Split

Break a string into parts at a delimiter.

33

Parse

Convert text into a typed value, such as a decimal price.

34

Culture

Regional formatting rules for numbers and dates; CultureInfo.InvariantCulture gives the same result on every machine.

35

Normalizing

Cleaning a value, for example by trimming and changing case, so equal values look equal.

36

Reject and continue

A policy that skips a bad record, records why, and keeps processing the rest.

37

Untrusted input

Data from outside the program that must be validated before it is used.

38

Allow-list

A validation rule that accepts only values known to be good.

39

Masking

Replacing most of a sensitive value, such as all but the last four digits of a card number.

40

Redaction

Removing sensitive content from text before it is shown or saved.

41

Injection

An attack in which input is treated as commands rather than as data.

42

Log

A record of events a program writes for later review.

43

Regular expression

A pattern language for matching text.

44

Match

A piece of text that satisfies a search pattern.

45

Capture group

A parenthesized part of a regular expression whose matched text can be read separately.

Lecture Slides

Chapter 9 Slides