Разделы презентаций


NET.C#.0 8. Managinge the File system

Содержание

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

Слайды и текст этой презентации

Слайд 1NET.C#.08. Managinge the File system

NET.C#.08. Managinge the File system

Слайд 2Managing the files
For many applications a common requirement is the

ability to 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

Managing the filesFor many applications a common requirement is the ability to interact with the file system:

Слайд 3.Net Classes that represent Files and Folders
Directory and File contain

only static 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 file
FileInfo myFile = new FileInfo(@”C:\Program Files\ReadMe.txt”);
myFile.CopyTo(@”D:\Copies\ReadMe.txt”);

//The same effect
File.Copy(@”C:\Program Files\ReadMe.txt”,@”D:\Copies\ReadMe.txt”);

.Net Classes that represent Files and FoldersDirectory and File contain only static methods. You use these classes

Слайд 4FileInfo and DirectoryInfo properties
You can use following properties

FileInfo and DirectoryInfo propertiesYou can use following properties

Слайд 5FileInfo and DirectoryInfo methods
You can also perform actions on the

file system object using the following methods:
// displays the creation

time of a file, then changes it and
// displays it again
FileInfo test = new FileInfo(@”C:\My Documents\MyFile.txt”);
Console.WriteLine(test.Exists.ToString());
Console.WriteLine(test.CreationTime.ToString());
test.CreationTime = new DateTime(2001, 1, 1, 7, 30, 0);
Console.WriteLine(test.CreationTime.ToString());
FileInfo and DirectoryInfo methodsYou can also perform actions on the file system object using the following methods://

Слайд 6Example: A File Browser
that presents a simple user interface that

allows you to browse around the file system, and view

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

Слайд 7Example: A File Browser
Step 1. Create the project as a

standard C# Windows application and add the
various text boxes

and the list boxes:

textBoxInput

textBoxFolder

buttonDisplay

buttonUp

listBoxFiles

listBoxFolders

textBoxFileName

textBoxCreationTime

textBoxFileSize

textBoxLastAccessTime

textBoxLastWriteTime

Step 2. Indicate that we will be using the System.IO namspace:

Using System.IO;

Example: A File BrowserStep 1. Create the project as a standard C# Windows application and add the

Слайд 8Example: A File Browser
Step 3. Add a member field to

the main form:
Step 4. Add event handlers for the user-generated

events:


public partial class Form1 : Form
{
private string currentFolderPath;

Stores the path 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

Example: A File BrowserStep 3. Add a member field to the main form:Step 4. Add event handlers

Слайд 9Example: A File Browser
Step 5. Add the methods that do

all the work

//clear the contents of all controls
protected void

ClearAllFields()
{
listBoxFolders.Items.Clear();
listBoxFiles.Items.Clear();
textBoxFolder.Text = “”;
textBoxFileName.Text = “”;
textBoxCreationTime.Text = “”;
textBoxLastAccessTime.Text = “”;
textBoxLastWriteTime.Text = “”;
textBoxFileSize.Text = “”;
}
Example: A File BrowserStep 5. Add the methods that do all the work//clear the contents of all

Слайд 10Example: A File Browser
Step 5. Add the methods that do

all the work

//Display information for a given file in the

text boxes
protected void DisplayFileInfo(string fileFullName)
{
FileInfo theFile = new FileInfo(fileFullName);
if (!theFile.Exists)
throw new FileNotFoundException(“File not found: “ + fileFullName);
textBoxFileName.Text = theFile.Name;
textBoxCreationTime.Text = theFile.CreationTime.ToLongTimeString();
textBoxLastAccessTime.Text = theFile.LastAccessTime.ToLongDateString();
textBoxLastWriteTime.Text = theFile.LastWriteTime.ToLongDateString();
textBoxFileSize.Text = theFile.Length.ToString() + “ bytes”;
}
Example: A File BrowserStep 5. Add the methods that do all the work//Display information for a given

Слайд 11Example: A File Browser
Step 5. Add the methods that do

all the work

//Display the contents of a given folder in

the two list boxes
protected void DisplayFolderList(string folderFullName)
{
DirectoryInfo theFolder = new DirectoryInfo(folderFullName);
if (!theFolder.Exists)
throw new DirectoryNotFoundException(“Folder not found: “
+ folderFullName);
ClearAllFields();
textBoxFolder.Text = theFolder.FullName;
currentFolderPath = theFolder.FullName;
// list all subfolders in folder
foreach(DirectoryInfo nextFolder in theFolder.GetDirectories())
listBoxFolders.Items.Add(nextFolder.Name);
// list all files in folder
foreach(FileInfo nextFile in theFolder.GetFiles())
listBoxFiles.Items.Add(nextFile.Name);
}
Example: A File BrowserStep 5. Add the methods that do all the work//Display the contents of a

Слайд 12Example: A File Browser
Step 5. Add the methods that do

all the work

//Display button handler
protected void OnDisplayButtonClick(object sender, EventArgs e)
{

string folderPath = textBoxInput.Text;
DirectoryInfo theFolder = new DirectoryInfo(folderPath);
if (theFolder.Exists)
{ DisplayFolderList(theFolder.FullName);return;}
FileInfo theFile = new FileInfo(folderPath);
if (theFile.Exists)
{ DisplayFolderList(theFile.Directory.FullName);
int index = listBoxFiles.Items.IndexOf(theFile.Name);
listBoxFiles.SetSelected(index, true);
return;
}
throw new FileNotFoundException(“There is no file or folder with “
+ “this name: “ + textBoxInput.Text);
}
Example: A File BrowserStep 5. Add the methods that do all the work//Display button handlerprotected void OnDisplayButtonClick(object

Слайд 13Example: A File Browser
Step 5. Add the methods that do

all the work

//Event handler that is called when an item

in the Files list
//box is selected
protected void OnListBoxFilesSelected(object sender, EventArgs e)
{
try
{
string selectedString = listBoxFiles.SelectedItem.ToString();
string fullFileName = Path.Combine(currentFolderPath,
selectedString);
DisplayFileInfo(fullFileName);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Example: A File BrowserStep 5. Add the methods that do all the work//Event handler that is called

Слайд 14Example: A File Browser
Step 5. Add the methods that do

all the work

//Event handler for the selection of a folder

in the Folder list
protected void OnListBoxFoldersSelected(object sender, EventArgs e)
{
try
{
string selectedString = listBoxFolders.SelectedItem.ToString();
string fullPathName = Path.Combine(currentFolderPath, selectedString);
DisplayFolderList(fullPathName);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Example: A File BrowserStep 5. Add the methods that do all the work//Event handler for the selection

Слайд 15Example: A File Browser
Step 5. Add the methods that do

all the work

//Event handler for Up button
protected void OnUpButtonClick(object sender,

EventArgs e)
{
try
{
string folderPath = new FileInfo(currentFolderPath).DirectoryName;
DisplayFolderList(folderPath);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Example: A File BrowserStep 5. Add the methods that do all the work//Event handler for Up buttonprotected

Слайд 16Reading and Writing to Files
Reading and writing to files is

in principle 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.

Reading and Writing to FilesReading and writing to files is in principle very simple; however, it is

Слайд 17Actual hierarchy of stream-related classes in the System.IO namespace.

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

Слайд 18Streams
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.

Streams FileStream — This class is intended for reading and writing binary data in a binary file.However,

Слайд 19Reading and Writing Text Files
StreamReader Sr = new StreaReader(@”c:\Documents\ReadMe.txt”);

//specify encoding

(ASCII, Unicode, UTF8)
StreamReader sr = new StreamReader(@”c:\Documents\ReadMe.txt”, Encoding.UTF8);
//
FileStream fs =

new FileStream(@”C:\My Documents\ReadMe.txt”,
FileMode.Open, FileAccess.Read, FileShare.None);
StreamReader sr = new StreamReader(fs);

StreamReader. The simplest constructor takes just a file name

Reading and Writing Text FilesStreamReader Sr = new StreaReader(@”c:\Documents\ReadMe.txt”);//specify encoding (ASCII, Unicode, UTF8)StreamReader sr = new StreamReader(@”c:\Documents\ReadMe.txt”,

Слайд 20Reading and Writing Text Files
void SaveFile()
{
StreamWriter sw = new

StreamWriter(chosenFile, false,
Encoding.Unicode);
foreach (string line in textBoxContents.Lines)
sw.WriteLine(line);
sw.Close();

}


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

Reading and Writing Text Filesvoid SaveFile(){ StreamWriter sw = new StreamWriter(chosenFile, false, Encoding.Unicode); foreach (string line in

Слайд 21Чтение и запись двоичных данных
string filePath = "...";
FileStream file =

new FileStream(filePath);
...
BinaryReader reader = new BinaryReader(file);
...
BinaryWriter writer = new BinaryWriter(file);
При

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

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

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

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

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


string destinationFilePath = @"C:\. . .\BinaryDataFile.bin";
byte[]

dataCollection = { 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 как параметр

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

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


string sourceFilePath = @"C:\. . .\BinaryDataFile.bin";
FileStream

sourceFile = 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 как параметр

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

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

Слайд 24Reading and writing Text Files
We can use StreamReader and StreamWriter

classes
string filePath = "...";
FileStream file = new FileStream(filePath );
...
StreamReader reader

= new StreamReader(file);
...
StreamWriter writer = new StreamWriter(file);

Close()

Peek()

Read()

ReadBlock()

EndOfStream

ReadLine()

ReadToEnd()

Reading and writing Text FilesWe can use StreamReader and StreamWriter classesstring filePath =

Слайд 25Reading and Writing Text Files


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

Create 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);
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();
Reading and Writing Text Filesstring sourceFilePath = @

Слайд 26Reading and Writing Text Files
string sourceFilePath = @"C:\. . .\TextDataFile.txt";
string

data;
// Create 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

Reading and Writing Text Filesstring sourceFilePath = @

Слайд 27Reading and Writing Text Files
string destinationFilePath = @"C:\. . .\TextDataFile.txt";
string

data = "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

Reading and Writing Text Filesstring destinationFilePath = @

Слайд 28Thank you for your attention

Thank you for your attention

Обратная связь

Если не удалось найти и скачать доклад-презентацию, Вы можете заказать его на нашем сайте. Мы постараемся найти нужный Вам материал и отправим по электронной почте. Не стесняйтесь обращаться к нам, если у вас возникли вопросы или пожелания:

Email: Нажмите что бы посмотреть 

Что такое TheSlide.ru?

Это сайт презентации, докладов, проектов в PowerPoint. Здесь удобно  хранить и делиться своими презентациями с другими пользователями.


Для правообладателей

Яндекс.Метрика