🔷 C#

C# (.NET) 中的文件操作:详细指南

What is it and why? (a real-life analogy)

Imagine you are writing a letter to a friend. You take a sheet of paper, write the text, fold it into an envelope, and send it. A week later, the friend opens the envelope and reads your message. In the programming world, a file is that sheet of paper, and your program is both the author of the letter and the reader at the same time.

Files come in different types: text files (like a diary), binary files (like a photo), structured files (like an Excel spreadsheet). But the essence is the same: to save information for a long time, so it doesn't disappear when you turn off the computer.

Why does a programmer need to know how to work with files?

  • Save settings — so the game remembers your level and number of lives.
  • Read data — load a list of students from a school register.
  • Logging — record when and who logged into the system.
  • Exchange information — export a report to Excel or import contacts.
💡 Important: Working with files is divided into two major stages: READING (we retrieve data from the file) and WRITING (we send data to the file). In this article, we will cover reading in detail.

Theory: how it works internally

When your program wants to read a file, a whole performance takes place involving the operating system, the hard drive, and the program itself. Let's take a look behind the scenes.

Streams — the main characters

Imagine a file is a huge pipe filled with water (data). To get a drink, you need a smaller pipe — a stream. In C#, any file is opened through a stream (Stream). A stream is a sequence of bytes that flows from a source to a receiver.

There are two types of streams:

  • Byte streams — work with raw bytes (0s and 1s). Suitable for images, videos, archives.
  • Character streams — work with text, automatically converting bytes into letters (taking encoding into account).

Encodings — why letters turn into gibberish

A computer doesn't understand letters. It only understands numbers. An encoding is a mapping table: the letter 'A' = number 65. If you write text in one encoding (e.g., Windows-1251) and read it in another (UTF-8), you'll get nonsense.

The most popular encoding today is UTF-8. It understands all the world's languages, including emojis. In C#, UTF-8 is used by default, but it's better to specify it explicitly.

File path — an address in the computer world

To open a file, you need to know its address. Paths can be:

  • Absolute — the full address from the root of the drive: C:UsersIvanDocuments otes.txt
  • Relative — the address relative to the program's folder: datasettings.txt
⚠️ Tip: Always use relative paths if the file is located next to the program. This way your code will work on any computer.

File open modes

When you open a file, you need to tell the system what you intend to do:

  • FileMode.Open — open an existing file (if the file doesn't exist — error).
  • FileMode.OpenOrCreate — open an existing file or create a new one.
  • FileMode.Append — open and append to the end.

Syntax in C# (.NET): all forms and variants

In C#, there are several ways to read a file. We'll look at all the main ones, from the simplest to the more flexible.

1. The File class — fast and simple

This class contains static methods. You don't need to create an object — just call the method and get the result.

Method What it does Returns
File.ReadAllText(path) Reads the entire file as a single string string
File.ReadAllLines(path) Reads all lines into an array string[]
File.ReadAllBytes(path) Reads all bytes (for binary files) byte[]

2. The StreamReader class — control over the process

If the file is large (millions of lines), reading it entirely into memory is dangerous — the program might crash. StreamReader reads line by line, saving memory.

Method Description
ReadLine() Reads one line up to the newline character
ReadToEnd() Reads everything to the end of the stream
Read() Reads one character
Peek() Looks at the next character without consuming it

3. Asynchronous reading — for modern applications

If the program works with a user interface (WPF, WinForms, ASP.NET), reading a file should not "freeze" the screen. Asynchronous methods solve this problem:

  • ReadAllTextAsync()
  • ReadLineAsync()
  • ReadToEndAsync()

4. The using statement — guaranteed file closure

A file is an operating system resource. If you open it and forget to close it, other programs won't be able to access it. using automatically closes the file, even if an error occurs.

//