Непотоковый файловый ввод-вывод

  • docx
  • 18.11.2021
Публикация на сайте для учителей

Публикация педагогических разработок

Бесплатное участие. Свидетельство автора сразу.
Мгновенные 10 документов в портфолио.

Иконка файла материала Л2-002149.docx

Непотоковый файловый ввод-вывод (2005)

Предоставляется статическим классом File. Этот класс не является наследником потоковых классов.

public static class File

 

Методы ввода/вывода:

 

 

 

ReadAllBytes

Opens a binary file, reads the contents of the file into a byte array, and then closes the file.

 

 

ReadAllLines (String)

Opens a text file, reads all lines of the file, and then closes the file.

 

 

ReadAllLines (String, Encoding)

Opens a file, reads all lines of the file with the specified encoding, and then closes the file.

 

 

ReadAllText (String)

Opens a text file, reads all lines of the file, and then closes the file.

 

 

ReadAllText (String, Encoding)

Opens a file, reads all lines of the file with the specified encoding, and then closes the file.

 

 

 

 

WriteAllBytes

Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.

 

 

 

 

WriteAllLines (String, String[ ])

Creates a new file, write the specified string array to the file, and then closes the file. If the target file already exists, it is overwritten.

 

 

 

WriteAllLines (String,          String[], Encoding)

Creates a new file, writes the specified string array to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten.

 

 

 

 

WriteAllText (String, String)

Creates a new file, writes the specified string to the file, and then closes the file.

If the target file already exists, it is overwritten.

 

 

 

WriteAllText (String,             String, Encoding)

Creates a new file, writes the specified string to the file using the specified encod- ing, and then closes the file. If the target file already exists, it is overwritten.

 

Другие методы:

 

Exists

Determines whether the specified file exists.

 

 

 

AppendAllText

Overloaded. Appends the specified stringto the file, creating the file if it does not already ex- ist.

 

Форматы методов:


У всех перечисленных ниже методов параметр path определяет путь к файлу

 

public static byte[ ] ReadAllBytes ( string path ) public static string[ ] ReadAllLines ( string path ) public static string ReadAllText ( string path )

 

public static void            WriteAllBytes ( string path, byte[ ] bytes ) public static void                       WriteAllLines ( string path, string[ ] contents ) public static void            WriteAllText ( string path, string contents )

 

Методы открывают файл, выполняют чтение/запись всего файла, а затем закрывают файл. И это все одним вызовом.

Методы Write… перезаписывают старые файлы и создают их, если они не существовали.

 

Для методов Read файлы должны существовать.

 

Метод WriteAllLines дописывает символы конца строки. При записи другими методами необходимо добавить символы конца строки вручную:

"\r\n" или Environment.NewLine.

 

Метод ReadAllLines разделяет строки по символам их конца.

 

Методы ReadAllLines и ReadAllBytes автоматически устанавливают размерность массива по фактическому количеству считанных элементов (строк, байтов).

 

Методы ReadAllText и WriteAllText работают с содержимым фай- ла как с одной строкой, не реагируя на символы конца строк.

 

Таблица исключений для метода ReadAllLines:

Exception type

Condition

ArgumentException

path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.

ArgumentNullException

path is a null reference.

PathTooLongException

The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.

DirectoryNotFoundException

The specified path is invalid (for exam- ple, it is on an unmapped drive).

IOException

An I/O error occurred while opening the file.


UnauthorizedAccessException

path specified a file that is read-only.

-or-

This operation is not supported on the current platform.

-or-

path specified a directory.

-or-

The caller does not have the required permission.

FileNotFoundException

The   file   specified  in   path  was   not found.

NotSupportedException

path is in an invalid format.

SecurityException

The caller does not have the required permission.

 

Пример использования методов WriteAllLines, ReadAllLines, AppendAll- Text и Exists:

using System; using System.IO; class Test

{

public static void Main()

{

string path = @"c:\temp\MyTest.txt";

 

// Текст добавляется в файл только один раз

if ( ! File.Exists (path) )

{

// Создать файл и записать строки. Закрыть файл. string[ ] createText = { "Hello", "And", "Welcome" }; File.WriteAllLines (path, createText);

}

 

// Этот текст будет добавляться при каждом запуске программы string appendText = "This is extra text" + Environment.NewLine; File.AppendAllText (path, appendText);

 

// Открыть файл, прочитать и закрыть. string[] readText = File.ReadAllLines (path);

 

foreach (string s in readText)

{

Console.WriteLine(s);

}

}

}

Hello And Welcome

This is extra text This is extra text


This is extra text

 

Пример использования методов WriteAllText и ReadAllText.

using System; using System.IO; using System.Text;

 

class Test

{

public static void Main()

{

string path = @"c:\temp\MyTest.txt";

 

if (!File.Exists(path))

{

// Создать файл и записать текст. Закрыть файл.

string createText = "Hello and Welcome" + Environment.NewLine; File.WriteAllText (path, createText);

}

 

string appendText = "This is extra text" + Environment.NewLine; File.AppendAllText(path, appendText);

 

// Открыть файл, прочитать и закрыть. string readText = File.ReadAllText(path); Console.WriteLine(readText);

}

}

 

Hello and Welcome This is extra text This is extra text