Скачать презентацию NET C 08 Managinge the File system Скачать презентацию NET C 08 Managinge the File system

С#Net_English_08.ppt

  • Количество слайдов: 28

NET. C#. 08. Managinge the File system NET. C#. 08. Managinge the File system

Managing the files For many applications a common requirement is the ability to interact Managing the files For many applications a common requirement is the ability to interact with the file system: q creation of new files q copying files q deleting files q moving files from one directory to another The classes that are used to browse around the file system and perform the operations are File, File. Info, Directory. Info, File. System. Info, Path File. System. Info – Base class that represents any file system object File. Info and File – These classes represent a file on the file system Directory. Info and Directory – These classes represent a folder on the file system Path – contains static method that you can use to manipulate pathnames

. 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 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 Directory. Info and File. Info implement the same public methods as Directory and File, but //Copying file the members of these classes are not static. You need to instantiate these classes before File. Info my. File = new File. Info(@”C: Program FilesRead. Me. txt”); each instance is associated with a particular folder or file. This means that these classes my. File. Copy. To(@”D: CopiesRead. Me. txt”); 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 //The same effect system object on construction, and then do not need to read that information again. File. Copy(@”C: Program FilesRead. Me. txt”, @”D: CopiesRead. Me. txt”); string source. File = ". . . "; string dest. File = ". . . "; bool overwrite = false; File. Copy(source. File, dest. File, overwrite); string file. Path = ". . . "; File. Info file = new File. Info(file. Path); string dest. Path = ". . . "; file. Copy. To(dest. Path);

File. Info and Directory. Info properties You can use following properties Name Description Creation. File. Info and Directory. Info properties You can use following properties Name Description Creation. Time file or folder was created Directory. Name Full pathname of the containing folder Parent The parent directory of a specified subdirectory Exists Whether file or folder exists Extension of the file; returns blank for folders Full. Name Full pathname of the file or folder Last. Access. Time file or folder was last accessed Name of the file or folder Root The root portion of the path Length The size of the file in bytes

File. Info and Directory. Info methods You can also perform actions on the file File. Info and Directory. Info methods You can also perform actions on the file system object using the following methods: Name Create() Description Creates a folder or empty file of the given name. For a File. Info this also returns a stream object to let you write to the file. Delete() Deletes the file or folder. For folders there is an option for the // displays the creation recursive. a file, then changes it and Delete to be time of // displays it again Move. To() Moves and/or renames the file or folder. File. Info test = new File. Info(@”C: My DocumentsMy. File. txt”); Copy. To() (File. Info only) Copies the file. Note that Console. Write. Line(test. Exists. To. String()); there is no copy Method for folders. If copying complete directory trees Console. Write. Line(test. Creation. Time. To. String()); you’ll need to individually Date. Time(2001, 1, new folders corresponding to test. Creation. Time = new copy each file and create 1, 7, 30, 0); the old folders. Console. Write. Line(test. Creation. Time. To. String()); Get. Directories() (Directory. Info only) Returns an array of Directory. Info objects representing all folders contained in this folder. Get. Files() (Directory. Info only) Returns an array of File. Info objects Representing all files contained in this folder.

Example: A File Browser that presents a simple user interface that allows you to Example: 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 Browser Step 1. Create the project as a standard C# Windows Example: A File Browser Step 1. Create the project as a standard C# Windows application and add the various text boxes and the list boxes: text. Box. Input text. Box. Folder button. Display button. Up list. Box. Files list. Box. Folders text. Box. File. Name text. Box. Creation. Time text. Box. File. Size text. Box. Last. Access. Time text. Box. Last. Write. Time Step 2. Indicate that we will be using the System. IO namspace: Using System. IO;

Example: A File Browser Step 3. Add a member field to the main form: Example: A File Browser Step 3. Add a member field to the main form: public partial class Form 1 : Form { private string current. Folder. Path; Stores the path of the folder whose contants are displayed in the list box Step 4. Add event handlers for the user-generated events: 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 Browser Step 5. Add the methods that do all the work Example: A File Browser Step 5. Add the methods that do all the work //clear the contents of all controls protected void Clear. All. Fields() { list. Box. Folders. Items. Clear(); list. Box. Files. Items. Clear(); text. Box. Folder. Text = “”; text. Box. File. Name. Text = “”; text. Box. Creation. Time. Text = “”; text. Box. Last. Access. Time. Text = “”; text. Box. Last. Write. Time. Text = “”; text. Box. File. Size. Text = “”; }

Example: A File Browser Step 5. Add the methods that do all the work Example: 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 Display. File. Info(string file. Full. Name) { File. Info the. File = new File. Info(file. Full. Name); if (!the. File. Exists) throw new File. Not. Found. Exception(“File not found: “ + file. Full. Name); text. Box. File. Name. Text = the. File. Name; text. Box. Creation. Time. Text = the. File. Creation. Time. To. Long. Time. String(); text. Box. Last. Access. Time. Text = the. File. Last. Access. Time. To. Long. Date. String(); text. Box. Last. Write. Time. Text = the. File. Last. Write. Time. To. Long. Date. String(); text. Box. File. Size. Text = the. File. Length. To. String() + “ bytes”; }

Example: A File Browser Step 5. Add the methods that do all the work Example: 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 Display. Folder. List(string folder. Full. Name) { Directory. Info the. Folder = new Directory. Info(folder. Full. Name); if (!the. Folder. Exists) throw new Directory. Not. Found. Exception(“Folder not found: “ + folder. Full. Name); Clear. All. Fields(); text. Box. Folder. Text = the. Folder. Full. Name; current. Folder. Path = the. Folder. Full. Name; // list all subfolders in folder foreach(Directory. Info next. Folder in the. Folder. Get. Directories()) list. Box. Folders. Items. Add(next. Folder. Name); // list all files in folder foreach(File. Info next. File in the. Folder. Get. Files()) list. Box. Files. Items. Add(next. File. Name); }

Example: A File Browser Step 5. Add the methods that do all the work Example: A File Browser Step 5. Add the methods that do all the work //Display button handler protected void On. Display. Button. Click(object sender, Event. Args e) { string folder. Path = text. Box. Input. Text; Directory. Info the. Folder = new Directory. Info(folder. Path); if (the. Folder. Exists) { Display. Folder. List(the. Folder. Full. Name); return; } File. Info the. File = new File. Info(folder. Path); if (the. File. Exists) { Display. Folder. List(the. File. Directory. Full. Name); int index = list. Box. Files. Items. Index. Of(the. File. Name); list. Box. Files. Set. Selected(index, true); return; } throw new File. Not. Found. Exception(“There is no file or folder with “ + “this name: “ + text. Box. Input. Text); }

Example: A File Browser Step 5. Add the methods that do all the work Example: 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 On. List. Box. Files. Selected(object sender, Event. Args e) { try { string selected. String = list. Box. Files. Selected. Item. To. String(); string full. File. Name = Path. Combine(current. Folder. Path, selected. String); Display. File. Info(full. File. Name); } catch(Exception ex) { Message. Box. Show(ex. Message); } }

Example: A File Browser Step 5. Add the methods that do all the work Example: 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 On. List. Box. Folders. Selected(object sender, Event. Args e) { try { string selected. String = list. Box. Folders. Selected. Item. To. String(); string full. Path. Name = Path. Combine(current. Folder. Path, selected. String); Display. Folder. List(full. Path. Name); } catch(Exception ex) { Message. Box. Show(ex. Message); } }

Example: A File Browser Step 5. Add the methods that do all the work Example: A File Browser Step 5. Add the methods that do all the work //Event handler for Up button protected void On. Up. Button. Click(object sender, Event. Args e) { try { string folder. Path = new File. Info(current. Folder. Path). Directory. Name; Display. Folder. List(folder. Path); } catch(Exception ex) { Message. Box. Show(ex. Message); } }

Reading and Writing to Files Reading and writing to files is in principle very Reading and Writing to Files Reading and writing to files is in principle very simple; however, it is not done through the Directory. Info or File. Info 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.

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

Streams • File. Stream — This class is intended for reading and writing binary Streams • File. Stream — 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. • Stream. Reader and Stream. Writer — These classes are designed specifically for reading from and writing to text files. stream.

Reading and Writing Text Files Stream. Reader. The simplest constructor takes just a file Reading and Writing Text Files Stream. Reader. The simplest constructor takes just a file name Stream. Reader Sr = new Strea. Reader(@”c: DocumentsRead. Me. txt”); //specify encoding (ASCII, Unicode, UTF 8) Stream. Reader sr = new Stream. Reader(@”c: DocumentsRead. Me. txt”, Encoding. UTF 8); // File. Stream fs = new File. Stream(@”C: My DocumentsRead. Me. txt”, File. Mode. Open, File. Access. Read, File. Share. None); Stream. Reader sr = new Stream. Reader(fs);

Reading and Writing Text Files Stream. Writer. Write each line of the text box Reading and Writing Text Files Stream. Writer. Write each line of the text box to a Stream. Writer steram void Save. File() { Stream. Writer sw = new Stream. Writer(chosen. File, false, Encoding. Unicode); foreach (string line in text. Box. Contents. Lines) sw. Write. Line(line); sw. Close(); }

Чтение и запись двоичных данных При построении объектам Binary. Reader и Binary. Writer предоставляется Чтение и запись двоичных данных При построении объектам Binary. Reader и Binary. Writer предоставляется поток, подключенный к источнику данных, из которого нужно читать или в который необходимо писать string file. Path = ". . . "; File. Stream file = new File. Stream(file. Path); . . . Binary. Reader reader = new Binary. Reader(file); . . . Binary. Writer writer = new Binary. Writer(file); Close() Base. Stream Read. Bytes() Read() Base. Stream Read. Byte() Write() Flush() Close() Seek() Когда использование объектов Binary. Reader или Binary. Writer завершено, необходимо вызвать метод Close, чтобы флешировать поток и освободить любые ресурсы, связанные с потоком Необходимо также закрыть объект File. Stream, предоставляющий данные для объектов Binary. Reader и Binary. Writer.

Чтение и запись двоичных данных string destination. File. Path = @ Чтение и запись двоичных данных string destination. File. Path = @"C: . . . Binary. Data. File. bin"; byte[] data. Collection = { 1, 4, 6, 7, 12, 33, 26, 98, 82, 101 }; Коллекция байт File. Stream dest. File = new File. Stream( destination. File. Path, File. Mode. Create Создание объекта File. Stream File. Access. Write); для взаимодействия Binary. Writer writer = new Binary. Writer(dest. File); с файловой системой foreach (byte data in data. Collection) { writer. Write(data); } Создание объекта Binary. Writer, writer. Close(); передавая объект File. Stream Запись каждого dest. File. Close(); байта в поток Закрыть оба потока для сброса данных в файл как параметр

Чтение и запись двоичных данных string source. File. Path = @ Чтение и запись двоичных данных string source. File. Path = @"C: . . . Binary. Data. File. bin"; File. Stream source. File = new File. Stream( Создание объекта File. Stream source. File. Path, для взаимодействия File. Mode. Open с файловой системой File. Access. Read); Binary. Reader reader = new Binary. Reader(source. File); int position = 0; Создание объекта Binary. Writer, int length = (int)reader. Base. Stream. Length; передавая объект File. Stream byte[] data. Collection = new byte[length]; как параметр int returned. Byte; while ((returned. Byte = reader. Read()) != -1) { data. Collection[position] = (byte)returned. Byte; position += sizeof(byte); } Если операции чтения из файла reader. Close(); или записи в файл генерируют source. File. Close(); Закрытие потоков для освобождения всех дескрипторов файлов исключение, следует убедиться, что потоки и дескрипторы файлов освобождены

Reading and writing Text Files We can use Stream. Reader and Stream. Writer classes Reading and writing Text Files We can use Stream. Reader and Stream. Writer classes string file. Path = ". . . "; File. Stream file = new File. Stream(file. Path ); . . . Stream. Reader reader = new Stream. Reader(file); . . . Stream. Writer writer = new Stream. Writer(file); Close() Read. Block() Peek() Read. Line() Read. To. End() End. Of. Stream Close() Write. Line() Flush() Auto. Flush Write() New. Line

Reading and Writing Text Files string source. File. Path = @ Reading and Writing Text Files string source. File. Path = @"C: . . . Text. Data. File. txt"; // Create a File. Stream object so that you can interact with the file system File. Stream source. File = new File. Stream( source. File. Path, // Pass in the source file path. File. Mode. Open, // Open an existing file. File. Access. Read); // Read an existing file. Stream. Reader reader = new Stream. Reader(source. File); String. Builder file. Contents = new String. Builder(); // Check to see if the end of the file has been reached. while (reader. Peek() != -1) { // Read the next character. file. Contents. Append((char)reader. Read()); } // Store the file contents in a new string variable. string data = file. Contents. To. String(); // Always close the underlying streams release any file handles. reader. Close(); source. File. Close();

Reading and Writing Text Files string source. File. Path = @ Reading and Writing Text Files string source. File. Path = @"C: . . . Text. Data. File. txt"; string data; // Create a File. Stream object so that you can // interact with the file system. File. Stream source. File = new File. Stream( source. File. Path, // Pass in the source file path. File. Mode. Open, // Open an existing file. File. Access. Read); // Read an existing file. Stream. Reader reader = new Stream. Reader(source. File); // Read the entire file into a single string variable. data = reader. Read. To. End(); // Always close the underlying streams release any file handles. reader. Close(); source. File. Close(); Класс Stream. Reader

Reading and Writing Text Files string destination. File. Path = @ Reading and Writing Text Files string destination. File. Path = @"C: . . . Text. Data. File. txt"; string data = "Hello, this will be written in plain text"; // Create a File. Stream object so that you can interact with the file // system. File. Stream dest. File = new File. Stream( destination. File. Path, // Pass in the destination path. File. Mode. Create, // Always create new file. File. Access. Write); // Only perform writing. // Create a new Stream. Writer object. Stream. Writer writer = new Stream. Writer(dest. File); // Write the string to the file. writer. Write. Line(data); // Always close the underlying streams to flush the data to the file // and release any file handles. writer. Close(); dest. File. Close(); Stream. Writer

Thank you for your attention Thank you for your attention