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

Создание списка каталогов

В следующем примере кода показано использование классов ввода/вывода для создания списка всех файлов с расширением ".exe" в каталоге.

Пример

-------

Robust Programming

In this example, the DirectoryInfo is the current directory, denoted by ("."), and the code lists all files in the current directory having a .exe extension, along with their file size, creation time, and name. Assuming that there were .exe files in the \Bin subdirectory of C:\MyDir, the output of this code might look like this:

953 7/20/2000 10:42 AM C:\MyDir\Bin\paramatt.exe

664 7/27/2000 3:11 PM C:\MyDir\Bin\tst.exe

403 8/8/2000 10:25 AM C:\MyDir\Bin\dirlist.exe

If you want a list of files in another directory, such as your C:\ root directory, pass the argument "C:\" into the executable generated by compiling this code, for example: "testApplication.exe C:\".

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

В этом примере DirectoryInfo является текущим каталогом, обозначенным ("."), а код создает список всех файлов с расширением .exe в текущем каталоге, вместе с их размерами, временем создания и именами. Если предположить, что существуют файлы .exe в поддиректории \Bin каталога C:\MyDir, результат выхода этого кода может выглядеть следующим образом:

953 7/20/2000 10:42 AM C:\MyDir\Bin\paramatt.exe

664 7/27/2000 3:11 PM C:\MyDir\Bin\tst.exe

403 8/8/2000 10:25 AM C:\MyDir\Bin\dirlist.exe

Если требуется список файлов другого каталога, такого как корневого каталога C:\, то передайте аргумент "C:\" в исполняемый файл путем компиляции этого кода, например: "testApplication.exe C:\".

How to: Read and Write to a Newly Created Data File

The BinaryWriter and BinaryReader classes are used for writing and reading data, rather than character strings. The following code example demonstrates writing data to and reading data from a new, empty file stream (Test.data). After creating the data file in the current directory, the associated BinaryWriter and BinaryReader are created, and the BinaryWriter is used to write the integers 0 through 10 to Test.data, which leaves the file pointer at the end of the file. After setting the file pointer back to the origin, the BinaryReader reads out the specified content.

Example

using System;

using System.IO;

class MyStream

{

private const string FILE_NAME = "Test.data";

public static void Main(String[] args)

{

// Create the new, empty data file.

if (File.Exists(FILE_NAME))

{

Console.WriteLine("{0} already exists!", FILE_NAME);

return;

}

FileStream fs = new FileStream(FILE_NAME, FileMode.CreateNew);

// Create the writer for data.

BinaryWriter w = new BinaryWriter(fs);

// Write data to Test.data.

for (int i = 0; i < 11; i++)

{

w.Write( (int) i);

}

w.Close();

fs.Close();

// Create the reader for data.

fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);

BinaryReader r = new BinaryReader(fs);

// Read data from Test.data.

for (int i = 0; i < 11; i++)

{

Console.WriteLine(r.ReadInt32());

}

r.Close();

fs.Close();

}

}

Robust Programming

If Test.data already exists in the current directory, an IOException is thrown. Use FileMode.Create to always create a new file without throwing an IOException.