Working with Files
Часть раздела Логика и управление потоком путешествия по C# на Coddy — урок 26 из 66.
В C# вы можете работать с файлами, используя классы из пространства имен System.IO. Два основных класса для текстовых файлов — StreamReader (для чтения) и StreamWriter (для записи).
Запись в файл:
using System.IO;
// Create a StreamWriter to write to a file
StreamWriter writer = new StreamWriter("myfile.txt");
// Write text to the file
writer.WriteLine("Hello, World!");
writer.WriteLine("This is line 2");
// Close the file
writer.Close();Чтение из файла:
using System.IO;
// Create a StreamReader to read from a file
StreamReader reader = new StreamReader("myfile.txt");
// Read all content from the file
string content = reader.ReadToEnd();
Console.WriteLine(content);
// Close the file
reader.Close();Чтение по строкам:
StreamReader reader = new StreamReader("myfile.txt");
// Read first line
string line1 = reader.ReadLine();
Console.WriteLine(line1);
// Read second line
string line2 = reader.ReadLine();
Console.WriteLine(line2);
reader.Close();Не забывайте всегда закрывать файлы с помощью Close(), когда закончите!
Задание
ЛегкоСоздайте метод с именем ReadFile, который:
- Принимает один строковый параметр:
filename - Читает содержимое из файла с использованием
StreamReader - Выводит содержимое в консоль
- Закрывает ридер
Шпаргалка
Работа с файлами с использованием пространства имен System.IO. Используйте StreamWriter для записи и StreamReader для чтения.
Запись в файл:
StreamWriter writer = new StreamWriter("myfile.txt");
writer.WriteLine("Hello, World!");
writer.Close();Чтение из файла:
StreamReader reader = new StreamReader("myfile.txt");
string content = reader.ReadToEnd();
Console.WriteLine(content);
reader.Close();Чтение построчно:
StreamReader reader = new StreamReader("myfile.txt");
string line = reader.ReadLine();
Console.WriteLine(line);
reader.Close();Ключевые методы:
WriteLine(text)- Записать строку в файлReadToEnd()- Прочитать весь текст из файлаReadLine()- Прочитать одну строку из файлаClose()- Закрыть файл (всегда делайте это!)
Попробуйте сами
using System;
using System.IO;
class Program
{
public static void ReadFile(string filename)
{
// Напишите свой код здесь
}
static void Main(string[] args)
{
string filename = Console.ReadLine();
ReadFile(filename);
}
}В этом уроке есть небольшой тест. Начните урок, чтобы ответить на вопросы и сохранить прогресс.
Все уроки раздела Логика и управление потоком
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety