C # File System Management

Source: Internet
Author: User

Managing the file system is primarily about managing files and directories in your computer, such as reading file information, deleting files, and reading directory information. These features are implemented primarily by manipulating files and directories from classes under the System.IO namespace

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

I. Directory classes and DirectoryInfo classes

  In the System.IO namespace, directory classes and DirectoryInfo classes are provided for catalog management. Using these two classes, you can create, move, browse, and even define a hidden directory and a read-only directory for the directory and its subdirectories.

All methods of the directory class are static methods, so they can be called without creating objects, which manipulate and query information for any directory, whereas the DirectoryInfo class requires instance members to invoke its methods to efficiently perform multiple operations on a directory. After the DirectoryInfo class is instantiated, its properties can also be used to obtain a status such as the creation time and last modified time of the catalog

  

  1. Common Properties of DirectoryInfo class

  The properties of the DirectoryInfo class can be used to get or set the relevant properties of the current directory, create an example, set up with properties such as attributes, and obtain information about the properties of the C:\Users\Eniac\Desktop\TestDirectory directory. The code is as follows:

stringDirpath ="c:\\users\\eniac\\desktop\\testdirectory";//absolute path to the directoryif(Directory.Exists (Dirpath))//If the directory exists{DirectoryInfo Info=NewDirectoryInfo (Dirpath);//initializing the current directory instanceInfo. Attributes = Fileattributes.readonly | Fileattributes.hidden;//use the Attributes property to set the directory to read-only and hidden     /*get information about the current directory using the properties of the DirectoryInfo instance*/Label1. Text+="Full Name:"+ info. FullName +"\ n"; Label1. Text+="Directory creation time:"+ info. Creationtime.tostring () +"\ n"; Label1. Text+="time of last access to this directory:"+ info. Lastaccesstime.tostring () +"\ n"; Label1. Text+="Last Modified directory time:"+ info. Lastwritetime.tostring () +"\ n"; Label1. Text+="DirectoryInfo Instance Name:"+ info. Name +"\ n"; Label1. Text+="Parent Directory:"+ info. Parent +"\ n"; Label1. Text+="path root section:"+ info. Root.tostring () +"\ n";}Else{Label1. Text="The directory does not exist, verify that the path is correct";}

Execution results such as:

    

  2. Common methods of directory class

  (1) Exists method

The Exists method receives a parameter that represents a string that contains the current directory path, and the Exists method returns a result indicating whether the directory exists and, if present, returns True, otherwise false. As the above example, the criteria of the IF statement:

if     (Directory.Exists (Dirpath)) // If the directory exists

(2) Creatdirectory method

The Creatdirectory method takes a string type parameter that creates a directory path, which creates a new directory based on this path, and returns a DirectoryInfo instance that returns a class instance representing the specified directory if the created directory already exists, and does not create a directory , and it does not produce an exception. The usual usage is as follows:

if (! Directory.Exists (Dirpath))   //{    directory.createdirectory (dirpath);}

(3) Delete method

The Delete method can delete the specified directory, which is an overloaded method that can receive either a parameter or two parameters. When the method receives a parameter, the parameter is the path of the specified directory, in which case only the specified empty directory can be deleted, if the directory is not empty, the system throws an exception, when the method receives two parameters, the second argument is a bool value, if true, you can delete the empty directory. The usual usage is as follows:

if (Directory.Exists (Dirpath))    // If the directory exists {    try    {        directory.delete (Dirpath,true);   Delete directories and all subdirectories and files in the directory     }    catch(Exception ex)    // the system throws an exception when an exception occurs     {        MessageBox.Show (ex. Message.tostring ());}    }    

(4) Move method

The Move method indicates that the specified directory is moved to a new location and provides the specified new directory name. The method can receive two parameters, where the first parameter represents the directory path to be moved, the second parameter represents the target path (plus the specified new directory name), and when the directory to be moved and the parent directory of the destination path are the same, move no longer moves the directory but renames the directory. The Move method cannot move directories between different logical drives in the following format:

string " C:\Users\Eniac\Desktop\dir1 " ; string " C:\Program Files\dir2 " ;D irectory. Move (DIRPATH1,DIRPATH2);  // move directory Dir1 to C:\Program files directory and rename to Dir2

In addition, the directory class has the following methods, not a detailed description:

Directory.GetFiles (Dirpath); // Gets the file name (file list, including subdirectories) of all files in the specified directory  Directory.getdirectories (Dirpath); // gets all subdirectory names under the specified directory // gets all subdirectory names and filenames in the specified directory

There are also methods in the DirectoryInfo class where the DirectoryInfo class object can manipulate the current file by using these methods, which are similar to the methods of the directory class and have many functions that are the same. When used specifically, if the user intends to reuse an object multiple times, consider using an instance method of DirectoryInfo instead of the corresponding static method of the Directory class, because the instance method of DirectoryInfo does not always require a security check, by default, This class will grant full read/write access to the new directory to all users

Because the methods in the DirectoryInfo class have many similarities to the methods of the directory class, they are only different in the way they are debugged, and the methods in that class are no longer explained.

    

Second, file class and FileInfo class

  The file class and the FileInfo class of the System.IO namespace provide relevant content about filesystem operations, such as creating, deleting, moving, and opening files

The file class operates in a similar way to the Directory class, and the methods in the file class are mostly static, whereas the FileInfo class is similar to the DirectoryInfo class explained above, and its properties and methods can be used only in instances where it is instantiated

  1. Common Properties of FileInfo class

The FileInfo class is primarily used to manipulate instance objects, similar to the operation of the DirectoryInfo class, which provides many properties that provide information about a file through the properties of the FileInfo class. Let's take a quick look at the properties of the FileInfo class using the following procedure:

Private voidButton1_Click (Objectsender, EventArgs e)//Select File{    /*a OpenFileDialog control is used here.*/    if(Openfiledialog1.showdialog ()! = DialogResult.OK)//exit if Open failed    {        return; } TextBox1.Text= Openfiledialog1.filename;//fill in the text box with the absolute path of the selected file}Private voidButton2_Click (Objectsender, EventArgs e)//Get more information{    stringFilePath = TextBox1.Text;//absolute path to fileFileInfo info =NewFileInfo (FilePath);//initializing the current file instanceLabel1. Text + ="········ File name:"+ info. Name +"\ n"; Label1. Text+="······ File full path:"+ info. FullName +"\ n"; Label1. Text+="···· Directory full path:"+ info. DirectoryName +"\ n"; Label1. Text+="······· File extension:"+ info. Extension +"\ n"; Label1. Text+="········ File Size:"+ info. Length/1024x768+"kb\n"; Label1. Text+="······ File creation time:"+ info. Creationtime.tostring () +"\ n"; Label1. Text+="time of last access to this file:"+ 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";}

Execution results such as:

  2. Common methods of File class

  The common methods of the file class are listed below:

File.exists (FilePath);//used to determine whether the specified file existsFile.create (FilePath);//create a file in the specified pathFile.delete (FilePath);//Delete the specified fileFile.move (FILEPATH1,FILEPATH2);//move the FilePath1 file to the specified filePath2 pathFile.Copy (FILEPATH1,FILEPATH2);//Copy the FilePath1 file to the specified filePath2 pathFile.appendalltext (filepath,string);//appends a string (the second argument) to the specified file, and if the file does not exist, this method first creates the file and appendsFile.ReadAllLines (FilePath);//reads all rows of the specified file one time, returns an array of strings, and the array elements are the contents of each rowFile.readalltext (FilePath);//reads all the contents of the specified file at once, returning a string containing the full text contentFile.writealllines (filepath,string[]);//writes each element of a string array one line at a time to the specified fileFile.writealltext (filepath,string);//writes a string (the second argument) to the specified file at once

The above four methods apply to the file read and write content is not a lot of cases, when the file read and write the time will be fine

There are also methods in the FileInfo class where the FileInfo class object can manipulate the current file by using these methods, which are similar to the method of the file class and have many functions that are the same. When used specifically, if the user intends to reuse an object multiple times, consider using an instance method of FileInfo instead of the corresponding static method of the file class, because the instance method of FileInfo does not always require a security check, and by default the class will grant all users full read/ Write access Permissions

Because the methods in the FileInfo class have many similarities to the methods of the file class, they are only different in the way they are debugged, and the methods in that class are no longer explained.

    

C # File System Management

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.