C # file system management,

Source: Internet
Author: User

C # file system management,

  Directory

  • Preface
  • Directory and DirectoryInfo
  • File and FileInfo
  • Path class

 

Preface

 

A file system manages files and directories on a computer, such as reading file information, deleting files, and reading directory information. These functions are implemented by the classes in the System. IO namespace to operate on files and directories.

The System. IO namespace provides necessary classes, methods, and attributes for directory and file operations.

 

 

Directory and DirectoryInfo

 

  In the System. IO namespace, the Directory class and DirectoryInfo class are provided for Directory management. You can use these two classes to create, move, and browse directories and Their subdirectories, and even define hidden and read-only directories.

All methods of the Directory class are static methods, so you can call them without creating an object. These methods can manipulate and query information of any Directory. The DirectoryInfo class can call its method only when an instance member is available, this effectively performs multiple operations on a directory. After the DirectoryInfo class is instantiated, you can use its properties to obtain the status of the Directory, such as the creation time and last modification time.

  

  1. common attributes of the DirectoryInfo class

  The DirectoryInfo class Attributes can be used to obtain or set the relevant Attributes of the current directory. The following creates an example to use Attributes and other Attributes to set and obtain C: \ Users \ Eniac \ Desktop \ TestDirectory. The Code is as follows:

String dirPath = "C: \ Users \ Eniac \ Desktop \ TestDirectory"; // the absolute path of the Directory if (Directory. exists (dirPath) // If the directory Exists {DirectoryInfo info = new DirectoryInfo (dirPath); // initialize the current directory instance info. attributes = FileAttributes. readOnly | FileAttributes. hidden; // use the Attributes attribute to set the directory to read-only and Hidden/* use the Attributes of the DirectoryInfo instance to obtain information about the current directory */label1.Text + = "all names:" + info. fullName + "\ n"; label1.Text + = "Directory Creation Time:" + info. creationTime. toString () + "\ n"; label1.Text + = "last time this directory was accessed:" + info. lastAccessTime. toString () + "\ n"; label1.Text + = "Last directory modification time:" + info. lastWriteTime. toString () + "\ n"; label1.Text + = "DirectoryInfo Instance name:" + info. name + "\ n"; label1.Text + = "parent directory:" + info. parent + "\ n"; label1.Text + = "path root:" + info. root. toString () + "\ n";} else {label1.Text = "this directory does not exist. Check whether the path is correct ";}

 

The execution result is as follows:

    

  2. Common Methods of Directory classes

  (1) Exists Method

The Exists method receives a parameter, which indicates the string containing the current directory path. The result returned by the Exists method indicates whether the directory Exists. If yes, true is returned. Otherwise, false is returned. The following are the conditions for determining if statements in the preceding example:

If (Directory. Exists (dirPath) // if the Directory Exists

 

(2) CreatDirectory Method

The CreatDirectory method accepts a String type parameter for creating a directory path. This method creates a new directory based on this path and returns a DirectoryInfo instance. If the Created directory already exists, the system returns a class instance that represents the specified directory. No directory is created or an exception occurs. The common usage is as follows:

If (! Directory. Exists (dirPath) // If the Directory does not exist, create the Directory {Directory. CreateDirectory (dirPath );}

 

(3) Delete Method

The Delete method can Delete a specified directory. This method is an overload method that can receive one or two parameters. When the method receives a parameter, this parameter is the path of the specified directory. In this case, only the specified empty directory can be deleted. If the directory is not empty, an exception is thrown; when this method receives two parameters, the second parameter is the bool value. If it is true, you can delete non-empty directories. The common usage is as follows:

If (Directory. exists (dirPath) // If the Directory Exists {try {Directory. delete (dirPath, true); // Delete the Directory and all subdirectories and files in the directory} catch (Exception ex) // when an Exception occurs, the system throws an Exception {MessageBox. show (ex. message. toString ());}}

 

(4) Move Method

The Move method moves the specified directory to a new location and provides a new directory name. This method can receive two parameters. The first parameter indicates the directory path to be moved, and the second parameter indicates the target path (with the specified new directory name ), when the directory to be moved is the same as the parent directory of the target path, Move will not Move the directory, but rename the directory. The Move method cannot Move directories between different logical drives. The format is as follows:

String dirPath1 = "C: \ Users \ Eniac \ Desktop \ dir1"; string dirPath2 = "C: \ Program Files \ dir2"; Directory. move (dirPath1, dirPath2); // Move the directory dir1 to the C: \ Program Files directory and rename it dir2

 

In addition, the Directory class has the following methods, so we will not detail them in detail:

Directory. getFiles (dirPath); // get the name of all files in the specified Directory (file list, including subdirectories) Directory. getDirectories (dirPath); // obtain all subdirectories in the specified Directory. getFileSystemEntries (dirPath); // obtain all the sub-directory names and file names in the specified directory

The preceding three methods have multiple parameter overload methods, which are used to search for related files or subdirectories in a specified directory. The multiple parameters indicate matching of search modes in a specified directory.

There are still some methods in the DirectoryInfo class. The DirectoryInfo class object can use these methods to operate the current file. These methods are similar to the Directory class methods, and many functions are the same. If you want to reuse an object multiple times, you can use the DirectoryInfo instance method instead of the static method of the Directory class, because the instance method of DirectoryInfo does not always require security check, by default, this class will grant all users full read/write access to the new directory.

The methods in the DirectoryInfo class have many similarities with those in the Directory class, but the debugging method is different. In this case, we will not explain the methods in this class.

    

 

File and FileInfo

 

  The File and FileInfo classes in the System. IO namespace provide File management related content, such as creating, deleting, moving, and opening files.

The operation methods of the File class are similar to those of the Directory class. Most of the methods in the File class are static methods, while the FileInfo class is similar to the DirectoryInfo class described above, attributes and methods can be used only when the instance is instantiated.

 

  1. common attributes of the FileInfo class

The FileInfo class is mainly used to operate instance objects. Similar to the DirectoryInfo class, it provides many attributes and obtains file information through the attributes of the FileInfo class. The following program briefly describes the attributes of the FileInfo class:

Private void button#click (object sender, EventArgs e) // select the file {/* an OpenFileDialog control is used here */if (openFileDialog1.ShowDialog ()! = DialogResult. OK) // exit {return;} textBox1.Text = openFileDialog1.FileName if opening fails; // enter the absolute path of the selected file in the text box} private void button2_Click (object sender, EventArgs e) // obtain detailed information {string filePath = textBox1.Text; // the absolute path of the file, FileInfo info = new FileInfo (filePath ); // initialize the current file instance label1.Text + = "· file name:" + info. name + "\ n"; label1.Text + = "· complete file path:" + info. fullName + "\ n"; label1.Text + = "· complete directory path:" + info. directoryName + "\ n"; label1.Text + = "· File Extension:" + info. extension + "\ n"; label1.Text + = "· file size:" + info. length/1024 + "KB \ n"; label1.Text + = "· File Creation Time:" + info. creationTime. toString () + "\ n"; label1.Text + = "last time this file was accessed:" + info. lastAccessTime. toString () + "\ n"; label1.Text + = "· the last time the file was written:" + info. lastWriteTime. toString () + "\ n"; label1.Text + = "· whether the file is read-only:" + info. isReadOnly + "\ n ";}

 

The execution result is as follows:

 

  2. Common File Methods

  Common Methods of File classes are listed below:

File. exists (filePath); // used to determine whether a specified File Exists. create (filePath); // Create a File in the specified path. delete (filePath); // Delete a specified File. move (filePath1, filePath2); // Move the filePath1 File to the specified filePath2 path File. copy (filePath1, filePath2); // Copy the filePath1 File to the specified filePath2 path File. appendAllText (filePath, String); // append the String (second parameter) to the specified File. If the File does not exist, this method creates the File first and then append the File. readAllLines (filePath); // read all rows of the specified File at a time and return a string array. The array element is the content File of each row. readAllText (filePath); // reads all the content of a specified File at a time, and returns a string File containing all the text content. writeAllLines (filePath, String []); // write each element of the String array into the specified File as a row at a time. writeAllText (filePath, String); // write the String (second parameter) to the specified file at a time.

 

The last four methods are applicable to the case where there are not many file reads and writes.

 

There are still some methods in the FileInfo class. The FileInfo class object can use these methods to operate the current File. These methods are similar to the File class methods, and many functions are the same. If you want to reuse an object multiple times, you can use the FileInfo instance method instead of the static method in the File class, because the FileInfo instance method does not always require security check, by default, this class will grant all users full read/write access to new files.

The methods in the FileInfo class have many similarities with those in the File class, but the debugging method is different. In this case, we will not explain the methods in this class.

    

 

Path class

 

  The Path class performs operations on String instances that contain file or directory Path information and performs these operations across platforms. On a platform that is not used, the Path strings may be different, and the file extension formats may be different, because the actions of the fields of these different Path classes and some members of the Path class are related to the platform.

All the members (methods and attributes) of the Path class are static, so they can be called without having to have a Path. These members allow users to perform common operations quickly and conveniently, for example, determine whether the file extension is part of a path, and combine the two strings into a path name.

Common methods and descriptions of the Path class are listed below:

Path. getExtension (path); // returns the extension Path of the specified path string. getFileNameWithoutExtension (path); // return the file name Path of the specified path string without the extension. getFileName (path); // returns the name of the specified Path string with the extension. getFullPath (path); // returns the absolute Path of the specified path string. changeExtension (path, extension); // change the extension of the path string

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.