Презентация СNet English 08

Скачать презентацию  СNet English 08 Скачать презентацию СNet English 08

snet_english_08.ppt

  • Размер: 1.3 Mегабайта
  • Количество слайдов: 28

Описание презентации Презентация СNet English 08 по слайдам

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

Managing the files For many applications a common requirement is the ability to interact with theManaging 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, 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 methods. You. 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 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 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); //Copying file File. Info my. File = new File. Info(@”C: \Program Files\Read. Me. txt”); my. File. Copy. To(@”D: \Copies\Read. Me. txt”); //The same effect File. Copy(@”C: \Program Files\Read. Me. txt”, @”D: \Copies\Read. Me. txt”);

File. Info and Directory. Info properties You can use following properties Name Description Creation. Time fileFile. 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 system objectFile. Info and Directory. Info methods You can also perform actions on the file system object using the following methods: Name Description Create() 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 Delete to be recursive. Move. To() Moves and/or renames the file or folder. Copy. To() (File. Info only) Copies the file. Note that there is no copy Method for folders. If copying complete directory trees you’ll need to individually copy each file and create new folders corresponding to the old folders. 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 R epresenting all files contained in this folder. // displays the creation time of a file, then changes it and // displays it again File. Info test = new File. Info(@”C: \My Documents\My. File. txt”); Console. Write. Line(test. Exists. To. String()); Console. Write. Line(test. Creation. Time. To. String()); test. Creation. Time = new Date. Time(2001, 1, 1, 7, 30, 0); Console. Write. Line(test. Creation. Time. To. String());

Example: A File Browser that presents a simple user interface that allows you to browse aroundExample: 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 applicationExample: 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: StepExample: 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 Form 1 : Form { private string current. Folder. Path; 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 Browser Step 5.  Add the methods that do all the work //clearExample: 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 //DisplayExample: 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 //DisplayExample: 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 //DisplayExample: 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 //EventExample: 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 //EventExample: 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 //EventExample: 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 simple; however,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 dataStreams • 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 Sr = new Strea. Reader(@”c: \Documents\Read. Me. txt”); //specifyReading and Writing Text Files Stream. Reader Sr = new Strea. Reader(@”c: \Documents\Read. Me. txt”); //specify encoding (ASCII, Unicode, UTF 8) Stream. Reader sr = new Stream. Reader(@”c: \Documents\Read. Me. txt”, Encoding. UTF 8); // File. Stream fs = new File. Stream(@”C: \My Documents\Read. Me. txt”, File. Mode. Open, File. Access. Read, File. Share. None); Stream. Reader sr = new Stream. Reader(fs); Stream. Reader. The simplest constructor takes just a file name

Reading and Writing Text Files void Save. File() {  Stream. Writer sw = new Stream.Reading and Writing Text Files 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(); }Stream. Writer. Write each line of the text box to a Stream. Writer steram

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

Чтение и запись двоичных данных string destination. File. Path = @C: \. . . \Binary. Data.Чтение и запись двоичных данных 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. Access. Write ); Binary. Writer writer = new Binary. Writer (dest. File); foreach (byte data in data. Collection) { writer. Write(data); } writer. Close (); dest. File. Close (); Закрыть оба потока для сброса данных в файл Запись каждого байта в поток Коллекция байт Создание объекта File. Stream для взаимодействия с файловой системой Создание объекта Binary. Writer , передавая объект File. Stream как параметр

Чтение и запись двоичных данных string source. File. Path = @C: \. . . \Binary. Data.Чтение и запись двоичных данных string source. File. Path = @»C: \. . . \Binary. Data. File. bin»; File. Stream source. File = new File. Stream ( source. File. Path, File. Mode. Open File. Access. Read ); Binary. Reader reader = new Binary. Reader (source. File); int position = 0; int length = (int)reader. Base. Stream. Length ; 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 (); Закрытие потоков для освобождения всех дескрипторов файлов Создание объекта File. Stream для взаимодействия с файловой системой Создание объекта Binary. Writer , передавая объект File. Stream как параметр Если операции чтения из файла или записи в файл генерируют исключение, следует убедиться, что потоки и дескрипторы файлов освобождены

Reading and writing Text Files We can use Stream. Reader and Stream. Writer classes string file.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() Peek() Read. Block() End. Of. Stream Read. Line() Read. To. End() Close() Flush() Write. Line() Auto. Flush New. Line

Reading and Writing Text Files string source. File. Path = @C: \. . . \Text. Data.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 = @C: \. . . \Text. Data.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 = @C: \. . . \Text. Data.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




  • Мы удаляем страницу по первому запросу с достаточным набором данных, указывающих на ваше авторство. Мы также можем оставить страницу, явно указав ваше авторство (страницы полезны всем пользователям рунета и не несут цели нарушения авторских прав). Если такой вариант возможен, пожалуйста, укажите об этом.