How to: Open and Append to a Log File 


Мы поможем в написании ваших работ!



ЗНАЕТЕ ЛИ ВЫ?

How to: Open and Append to a Log File



StreamWriter and StreamReader write characters to and read characters from streams. The following code example opens the log.txt file for input, or creates the file if it does not already exist, and appends information to the end of the file. The contents of the file are then written to standard output for display. As an alternative to this example, the information could be stored as a single string or string array, and the WriteAllText or WriteAllLines method could be used to achieve the same functionality.

Example

using System; using System.IO; class DirAppend { public static void Main(String[] args) { using (StreamWriter w = File.AppendText("log.txt")) { Log ("Test1", w); Log ("Test2", w); // Close the writer and underlying file. w.Close(); } // Open and read the file. using (StreamReader r = File.OpenText("log.txt")) { DumpLog (r); } } public static void Log (String logMessage, TextWriter w) { w.Write("\r\nLog Entry: "); w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString()); w.WriteLine(":"); w.WriteLine(":{0}", logMessage); w.WriteLine ("-------------------------------"); // Update the underlying file. w.Flush(); } public static void DumpLog (StreamReader r) { // While not at the end of the file, read and write lines. String line; while ((line=r.ReadLine())!=null) { Console.WriteLine(line); } r.Close(); } }

Открытие файла журнала и добавление в него данных

Классы StreamWriter и StreamReader предназначены для записи и чтения знаков из потоков. В следующем примере кода открывается файл log.txt в режиме ввода данных (если такого файла не существует, то он будет создан) и добавляется информация в конец файла. Затем содержимое файла передается для отображения в стандартный поток вывода. В качестве альтернативы данные здесь могут храниться как одна строка или как массив строк, а для обеспечения той же функциональности может быть использован метод WriteAllText WriteAllLines.

Пример

ß------


How to: Write Text to a File

The following code examples show how to write text to a text file.

The first example shows how to add text to an existing file. The second example shows how to create a new text file and write a string to it. Similar functionality can be provided by the WriteAllText methods.

Example

using System; using System.IO; class Test { public static void Main() { // Create an instance of StreamWriter to write text to a file. // The using statement also closes the StreamWriter. using (StreamWriter sw = new StreamWriter("TestFile.txt")) { // Add some text to the file. sw.Write("This is the "); sw.WriteLine("header for the file."); sw.WriteLine("-------------------"); // Arbitrary objects can also be written to the file. sw.Write("The date is: "); sw.WriteLine(DateTime.Now); } } }

 

using System; using System.IO; public class TextToFile { private const string FILE_NAME = "MyFile.txt"; public static void Main(String[] args) { if (File.Exists(FILE_NAME)) { Console.WriteLine("{0} already exists.", FILE_NAME); return; } using (StreamWriter sw = File.CreateText(FILE_NAME)) { sw.WriteLine ("This is my file."); sw.WriteLine ("I can write ints {0} or floats {1}, and so on.", 1, 4.2); sw.Close(); } } }

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

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

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

 


 

ß--------

 

Надежное программирование

Этот код создает поток StreamReader, который указывает на файл MyFile.txt посредством вызова метода File..::.OpenText. Метод StreamReader..::.ReadLine возвращает каждую строку файла в виде строки. Когда знаки для чтения заканчиваются, выводится соответствующее информационное сообщение, после чего поток закрывается.

 



Поделиться:


Последнее изменение этой страницы: 2017-01-19; просмотров: 102; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 3.147.66.178 (0.005 с.)