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


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



ЗНАЕТЕ ЛИ ВЫ?

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.


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

Классы 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); } } } }

 


Копирование каталогов

В этом примере демонстрируется использование классов ввода-вывода для копирования каталога с одного места на другое. В этом примере пользователь может выбирать, следует ли также копировать подкаталоги. Если подкаталоги копируются, то в этом примере метод рекурсивно копирует их путем вызова самого себя для каждого последующего подкаталога до тех пор, пока не останется ни одного каталога для копирования.

Пример

ß---------



Поделиться:


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

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