managing File system

Содержание

Слайд 2

Managing the files

For many applications a common requirement is the ability to

Managing the files For many applications a common requirement is the ability
interact with the file system:
creation of new files
copying files
deleting files
moving files from one directory to another

The classes that are used to browse around the file system and perform the operations are File, FileInfo, Directory, DirectoryInfo, FileSystemInfo, Path

FileSystemInfo – Base class that represents any file system object

FileInfo and File – These classes represent a file on the file system

DirectoryInfo and Directory – These classes represent a folder on the file system

Path – contains static method that you can use to manipulate pathnames

Слайд 3

.Net Classes that represent Files and Folders

Directory and File contain only static

.Net Classes that represent Files and Folders Directory and File contain only
methods. You use these classes by supplying the path to the appropriate file system object. If you only want to do one operation on a folder or file then using these classes is more efficient, because it saves the overhead of instantiating a .NET class

DirectoryInfo and FileInfo implement the same public methods as Directory and File, but the members of these classes are not static. You need to instantiate these classes before each instance is associated with a particular folder or file. This means that these classes are more efficient if you’re performing multiple operations using the same object, because they read in the authentication and other information for the appropriate file system object on construction, and then do not need to read that information again.

string sourceFile = "...";
string destFile = "...";
bool overwrite = false;
File.Copy(sourceFile, destFile, overwrite);

string filePath = "...";
FileInfo file = new FileInfo(filePath);
string destPath = "...";
file.CopyTo(destPath);

//Copying fileFileInfo myF
ile = new FileInfo(@”C:\
Program Files\ReadMe.tx
t”);myFile.CopyTo(@”D:\Copies\ReadMe.txt”);

Слайд 4

FileInfo and DirectoryInfo properties

You can use following properties

FileInfo and DirectoryInfo properties You can use following properties

Слайд 5

FileInfo and DirectoryInfo methods

You can also perform actions on the file system

FileInfo and DirectoryInfo methods You can also perform actions on the file
object using the following methods:

// displays the creation t
ime of a file, then chan
ges it and// displays i
t againFileInfo test = new FileInfo(@”C:\My

Слайд 6

Example: A File Browser

that presents a simple user interface that allows you

Example: A File Browser that presents a simple user interface that allows
to browse around the file system, and view the creation time, last access time, last write time, and size of files

Слайд 7

Example: A File Browser

Step 1. Create

textBoxInput

textBoxFolder

buttonDisplay

buttonUp

listBoxFiles

listBoxFolders

textBoxFileName

textBoxCreationTime

textBoxFileSize

textBoxLastAccessTime

textBoxLastWriteTime

Step 2. Indica

Example: A File Browser Step 1. Create textBoxInput textBoxFolder buttonDisplay buttonUp listBoxFiles

Слайд 8

Example: A File Browser

Step 3. Add a

Step 4. Add ev

Stores the path

Example: A File Browser Step 3. Add a Step 4. Add ev
of the folder whose contants are displayed in the list box

User clicks the Display button

User clicks on a file name in the Files list box

User clicks on a folder name in the Folders list box

User clicks on the Up button

Слайд 9

Example: A File Browser

Step 5. Add t

//clear the contents of al
l controls

Example: A File Browser Step 5. Add t //clear the contents of
protected voi
d ClearAllFields() {
listBoxFolders.Items.Clear(); listBoxF

Слайд 10

Example: A File Browser

Step 5. Add t

//Display information for
a given file

Example: A File Browser Step 5. Add t //Display information for a
in the text
boxesprotected void Di
splayFileInfo(string fileFullName){FileInfo

Слайд 11

Example: A File Browser

Step 5. Add t

//Display the contents of
a given

Example: A File Browser Step 5. Add t //Display the contents of
folder in the tw
o list boxesprotected v
oid DisplayFolderList(string folderFullName

Слайд 12

Example: A File Browser

Step 5. Add t

//Display button handlerpr
otected void OnDisplayBu
ttonClick(object sender
,

Example: A File Browser Step 5. Add t //Display button handlerpr otected
EventArgs e){ string folderPath = textBo

Слайд 13

Example: A File Browser

Step 5. Add t

//Event handler that is ca
lled when

Example: A File Browser Step 5. Add t //Event handler that is
an item in the
Files list//box is sel
ectedprotected void OnListBoxFilesSelected(

Слайд 14

Example: A File Browser

Step 5. Add t

//Event handler for the se
lection of

Example: A File Browser Step 5. Add t //Event handler for the
a folder in t
he Folder listprotected
void OnListBoxFoldersSelected(object sende

Слайд 15

Example: A File Browser

Step 5. Add t

//Event handler for Up but
tonprotected void

Example: A File Browser Step 5. Add t //Event handler for Up
OnUpBu
ttonClick(object sender
, EventArgs e){try { string folderPath = n

Слайд 16

Reading and Writing to Files

Reading and writing to files is in principle

Reading and Writing to Files Reading and writing to files is in
very simple; however, it is not done through the DirectoryInfo or FileInfo objects. it is done through a number of classes that represent a generic concept called a stream.

A stream is an object used to transfer data.
The data can be transferred in one of two directions:
If the data is being transferred from some outside source into your program, then we talk about reading from the stream.
If the data is being transferred from your program to some outside source, then we talk about writing to the stream.

Слайд 17

Actual hierarchy of stream-related classes in the System.IO namespace.

Actual hierarchy of stream-related classes in the System.IO namespace.

Слайд 18

Streams

FileStream — This class is intended for reading and writing binary

Streams FileStream — This class is intended for reading and writing binary
data in a binary file.
However, you can also use it to read from or write to any file.
StreamReader and StreamWriter — These classes are designed specifically for reading from and writing to text files.stream.

Слайд 19

Reading and Writing Text Files

StreamReader Sr = new St
reaReader(@”c:\Documents\ReadMe.txt”);//spe
cif
y encoding (ASCII, Unicode,

Reading and Writing Text Files StreamReader Sr = new St reaReader(@”c:\Documents\ReadMe.txt”);//spe cif
UTF8)StreamReader
sr
= new StreamReader(@”c:\Documents\ReadMe.txt

StreamReader. The simplest constructor takes just a file name

Слайд 20

Reading and Writing Text Files

void SaveFile(){ Stream
Writer sw = new StreamWriter(chosenFile, fa
lse
,

Reading and Writing Text Files void SaveFile(){ Stream Writer sw = new
Encoding.Unicode); foreach (string line i
n t
extBoxContents.Lines) sw.WriteLine(line); s

StreamWriter. Write each line of the text box to a StreamWriter steram

Слайд 21

Чтение и запись двоичных данных

string filePath = "...";
FileStream file = new FileStream(filePath);
...
BinaryReader

Чтение и запись двоичных данных string filePath = "..."; FileStream file =
reader = new BinaryReader(file);
...
BinaryWriter writer = new BinaryWriter(file);

При построении объектам BinaryReader и BinaryWriter предоставляется поток, подключенный к источнику данных, из которого нужно читать или в который необходимо писать

Когда использование объектов BinaryReader или BinaryWriter завершено, необходимо вызвать метод Close, чтобы флешировать поток и освободить любые ресурсы, связанные с потоком

Необходимо также закрыть объект FileStream, предоставляющий данные для объектов BinaryReader и BinaryWriter.

Слайд 22

Чтение и запись двоичных данных
string destinationFilePath = @"C:\. . .\BinaryDataFile.bin";
byte[] dataCollection =

Чтение и запись двоичных данных string destinationFilePath = @"C:\. . .\BinaryDataFile.bin"; byte[]
{ 1, 4, 6, 7, 12, 33, 26, 98, 82, 101 };
FileStream destFile = new FileStream(
destinationFilePath,
FileMode.Create
FileAccess.Write);
BinaryWriter writer = new BinaryWriter(destFile);
foreach (byte data in dataCollection)
{
writer.Write(data);
}
writer.Close();
destFile.Close();

Закрыть оба потока для сброса данных в файл

Запись каждого байта в поток

Коллекция байт

Создание объекта FileStream для взаимодействия с файловой системой

Создание объекта BinaryWriter, передавая объект FileStream как параметр

Слайд 23

Чтение и запись двоичных данных
string sourceFilePath = @"C:\. . .\BinaryDataFile.bin";
FileStream sourceFile =

Чтение и запись двоичных данных string sourceFilePath = @"C:\. . .\BinaryDataFile.bin"; FileStream
new FileStream(
sourceFilePath,
FileMode.Open
FileAccess.Read);
BinaryReader reader = new BinaryReader(sourceFile);
int position = 0;
int length = (int)reader.BaseStream.Length;
byte[] dataCollection = new byte[length];
int returnedByte;
while ((returnedByte = reader.Read()) != -1)
{
dataCollection[position] = (byte)returnedByte;
position += sizeof(byte);
}
reader.Close();
sourceFile.Close();

Закрытие потоков для освобождения всех дескрипторов файлов

Создание объекта FileStream для взаимодействия с файловой системой

Создание объекта BinaryWriter, передавая объект FileStream как параметр

Если операции чтения из файла или записи в файл генерируют исключение, следует убедиться, что потоки и дескрипторы файлов освобождены

Слайд 24

Reading and writing Text Files

We can use StreamReader and StreamWriter classes

string filePath

Reading and writing Text Files We can use StreamReader and StreamWriter classes
= "...";
FileStream file = new FileStream(filePath );
...
StreamReader reader = new StreamReader(file);
...
StreamWriter writer = new StreamWriter(file);

Close()

Peek()

Read()

ReadBlock()

EndOfStream

ReadLine()

ReadToEnd()

Слайд 25

Reading and Writing Text Files
string sourceFilePath = @"C:\. . .\TextDataFile.txt";
// Create a

Reading and Writing Text Files string sourceFilePath = @"C:\. . .\TextDataFile.txt"; //
FileStream object so that you can interact with the file system
FileStream sourceFile = new FileStream(
sourceFilePath, // Pass in the source file path.
FileMode.Open, // Open an existing file.
FileAccess.Read);// Read an existing file.
StreamReader reader = new StreamReader(sourceFile);
StringBuilder fileContents = new StringBuilder();
// Check to see if the end of the file has been reached.
while (reader.Peek() != -1)
{
// Read the next character.
fileContents.Append((char)reader.Read());
}
// Store the file contents in a new string variable.
string data = fileContents.ToString();
// Always close the underlying streams release any file handles.
reader.Close();
sourceFile.Close();

Слайд 26

Reading and Writing Text Files

string sourceFilePath = @"C:\. . .\TextDataFile.txt";
string data;
// Create

Reading and Writing Text Files string sourceFilePath = @"C:\. . .\TextDataFile.txt"; string
a FileStream object so that you can
// interact with the file system.
FileStream sourceFile = new FileStream(
sourceFilePath, // Pass in the source file path.
FileMode.Open, // Open an existing file.
FileAccess.Read);// Read an existing file.
StreamReader reader = new StreamReader(sourceFile);
// Read the entire file into a single string variable.
data = reader.ReadToEnd();
// Always close the underlying streams release any file handles.
reader.Close();
sourceFile.Close();

Класс StreamReader

Слайд 27

Reading and Writing Text Files

string destinationFilePath = @"C:\. . .\TextDataFile.txt";
string data =

Reading and Writing Text Files string destinationFilePath = @"C:\. . .\TextDataFile.txt"; string
"Hello, this will be written in plain text";
// Create a FileStream object so that you can interact with the file
// system.
FileStream destFile = new FileStream(
destinationFilePath, // Pass in the destination path.
FileMode.Create, // Always create new file.
FileAccess.Write); // Only perform writing.
// Create a new StreamWriter object.
StreamWriter writer = new StreamWriter(destFile);
// Write the string to the file.
writer.WriteLine(data);
// Always close the underlying streams to flush the data to the file
// and release any file handles.
writer.Close();
destFile.Close();

StreamWriter

Имя файла: managing-File-system.pptx
Количество просмотров: 150
Количество скачиваний: 0