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

Считывание из нового файла данных и запись в этот файл

Классы BinaryWriter и BinaryReader используются для записи и чтения данных вместо строк символов. В следующем примере кода представлены запись и чтение данных из нового пустого файлового потока (Test.data). После создания файла данных в текущем каталоге создаются соответствующие классы BinaryWriter и BinaryReader. Класс BinaryWriter используется для записи целых чисел от 0 до 10 в файл Test.data, при этом указатель устанавливается в конец файла. После установки файлового указателя в исходную позицию экземпляр класса BinaryReader считывает заданное содержимое.

Пример

-------

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

Если файл Test.data уже существует в текущем каталоге, создается исключение IOException. Используйте метод FileMode.Create, чтобы всегда создавать новый файл без вывода исключения IOException.

How to: Copy Directories

This example demonstrates how to use I/O classes to copy a directory from one location to another. In this example, the user can specify whether to also copy the subdirectories. If the subdirectories are copied, the method in this example recursively copies them by calling itself on each subsequent subdirectory until there are no more to copy.

Example

using System;

using System.IO;

class DirectoryCopyExample

{

static void Main()

{

DirectoryCopy(".", @".\temp", true);

}

private static void DirectoryCopy(

string sourceDirName, string destDirName, bool copySubDirs)

{

DirectoryInfo dir = new DirectoryInfo(sourceDirName);

DirectoryInfo[] dirs = dir.GetDirectories();

// If the source directory does not exist, throw an exception.

if (!dir.Exists)

{

throw new DirectoryNotFoundException(

"Source directory does not exist or could not be found: "

+ sourceDirName);

}

// If the destination directory does not exist, create it.

if (!Directory.Exists(destDirName))

{

Directory.CreateDirectory(destDirName);

}

// Get the file contents of the directory to copy.

FileInfo[] files = dir.GetFiles();

foreach (FileInfo file in files)

{

// Create the path to the new copy of the file.

string temppath = Path.Combine(destDirName, file.Name);

// Copy the file.

file.CopyTo(temppath, false);

}

// If copySubDirs is true, copy the subdirectories.

if (copySubDirs)

{

foreach (DirectoryInfo subdir in dirs)

{

// Create the subdirectory.

string temppath = Path.Combine(destDirName, subdir.Name);

// Copy the subdirectories.

DirectoryCopy(subdir.FullName, temppath, copySubDirs);

}

}

}

}