Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_Prog_Guide.doc
Скачиваний:
16
Добавлен:
16.11.2019
Размер:
6.22 Mб
Скачать

Запись текста в файл

Следующие примеры кода демонстрируют, как записать текст в текстовый файл.

В первом примере показано, как добавить текст в существующий файл. Во втором примере показано, как создать новый текстовый файл и записать строку в него. Аналогичные функции предоставляются методами WriteAllText.

Пример

----

How to: Read Text from a File

The following code examples show how to read text from a text file. The second example notifies you when the end of the file is detected. This functionality can also be achieved by using the ReadAllLines or ReadAllText methods.

Example

using System;

using System.IO;

class Test

{

public static void Main()

{

try

{

// Create an instance of StreamReader to read from a file.

// The using statement also closes the StreamReader.

using (StreamReader sr = new StreamReader("TestFile.txt"))

{

String line;

// Read and display lines from the file until the end of

// the file is reached.

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

{

Console.WriteLine(line);

}

}

}

catch (Exception e)

{

// Let the user know what went wrong.

Console.WriteLine("The file could not be read:");

Console.WriteLine(e.Message);

}

}

}

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

В следующих примерах кода показаны способы чтения текста из текстового файла. Во втором примере программа выдает сообщение об обнаружении конца файла. Эту функциональную возможность можно получить с помощью метода 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.

--------