logo search
CSharp_Prog_Guide

Считывание текста из файла

В следующих примерах кода показаны способы чтения текста из текстового файла. Во втором примере программа выдает сообщение об обнаружении конца файла. Эту функциональную возможность можно получить с помощью метода ReadAllLines или метода ReadAllText.

Пример

-------

using System;

using System.IO;

public class TextFromFile

{

private const string FILE_NAME = "MyFile.txt";

public static void Main(String[] args)

{

if (!File.Exists(FILE_NAME))

{

Console.WriteLine("{0} does not exist.", FILE_NAME);

return;

}

using (StreamReader sr = File.OpenText(FILE_NAME))

{

String input;

while ((input=sr.ReadLine())!=null)

{

Console.WriteLine(input);

}

Console.WriteLine ("The end of the stream has been reached.");

sr.Close();

}

}

Robust Programming

This code creates a StreamReader that points to MyFile.txt through a call to File..::.OpenText. StreamReader..::.ReadLine returns each line as a string. When there are no more characters to read, a message is displayed to that effect, and the stream is closed.

--------