[Switch] C # path/file/directory/I/O Common Operations Summary

Source: Internet
Author: User

File operations are very basic and important content in the program, while paths, files, directories, and I/O are common topics in file operations, I would like to summarize these common problems and try to provide some solutions for each problem. Even if you do not have the answer you want, I hope to provide you with some useful ideas, if you have good suggestions, please leave a message to improve the content.
Main content:
1. Path-related operations, such as determining whether the path is legal, path type, specific part of the path, merged path, and system folder path;
2. Related General file dialog box, which can help us operate the files and directories in the file system;
3. Operations on files, directories, and drives, such as obtaining basic information about them, obtaining and setting properties of files and directories, and file version information,
Search for files and directories, file determination, etc., copy, move, delete, rename files and directories;
4. Read and Write files, including temporary files and random file names;
5. File System Monitoring;
Write down the first two parts.
1. Path-related operations
Question 1: how to determine whether a given path is valid/valid;
Solution: Use path. getinvalidpathchars or path. getinvalidfilenamechars to obtain invalid path/file name characters.
Determine whether the path contains invalid characters;
Question 2: How to determine whether a path string represents a directory or a file;
1. Use directory. exists or file. exist. If the former is true, the path indicates the directory. If the former is true, the path indicates the file;
2. The disadvantage of the above method is that it cannot process non-existing files or directories. You can use the path. getfilename method to obtain
It contains the file name. If a path is not empty but the file name is empty, it indicates the Directory; otherwise, it indicates the file;
Question 3: How to obtain a specific part of a path (such as a file name or extension );
The following are some related methods:
Path. getdirectoryname: returns the directory information of the specified path string;
Path. getextension: returns the extension of the specified path string;
Path. getfilename: returns the name and extension of the specified path string;
Path. getfilenamewithoutextension: returns the name of the path string without the extension;
Path. getpathroot: obtains the root directory information of the specified path;
(For more information, see msdn)
Question 4: How to accurately merge two paths without worrying about the annoying "\" character;
Using the path. Combine method, it will help you deal with annoying "\";
Question 5: How to obtain the path of the system directory (such as desktop, my documents, and temporary folders );
The following describes the attributes and methods of the system. Environment class:
Environment. systemdirectory attributes: Obtain the fully qualified path of the system directory;
Environment. getfolderpath method: the parameter type accepted by this method is environment. specialfolder enumeration,
This method can be used to obtain a large number of system folders, such as my computer, my computer, desktop, and system directory;
(For more information, see msdn );
Path. gettemppath method: return the path of the temporary folder of the current system;
Question 6: How can I determine whether a path is an absolute path or a relative path;
Use path. ispathrooted;
Question 7: How to read or set the current directory;
Use the getcurrentdirectory and setcurrentdirectory methods of the Directory class;
Question 8: How to Use relative paths;
After setting the current directory (see question 7), you can use the relative path. For a relative path, we can
Use the path. getfullpath method to obtain its fully qualified path (absolute path ).
Note: If you plan to use a relative path, we recommend that you set the working directory as the common starting point for each interaction file. Otherwise,
Some hidden security risks are exploited by malicious users to access system files.
More information:
Generally, we can use the system. Io. Path class to process paths. This class provides a set of methods and attributes used to perform operations on strings that contain file or directory path information. These operations are executed in a cross-platform manner, and these methods and attributes are static.
Note that the path is only a string that provides the file or directory location. The path does not need to point to the location on the disk. For example, the path can be mapped to a location in the memory or on the device. The exact path format is determined by the current platform. For example, on some systems, a path can start with a drive letter or volume number, and this element does not exist in other systems. In some systems, file paths can contain extensions that indicate the types of information stored in files. The format of the file extension is platform-related. For example, some systems limit the extension length to 3 characters, while other systems do not. The current platform also determines the character set used to separate the elements in the path, and determines the character set that cannot be used when the specified path. Because of these differences, the field of the path class and the exact behavior of some members of the path class are related to the platform.
The path can contain absolute or relative location information. The absolute path specifies a complete location: the file or directory can be uniquely identified, regardless of the current location. Partial location specified by relative path: when the object specified by relative path is located, the current location is used as the starting point.
Most members of the path class do not interact with the file system and do not verify whether the file specified by the path string exists. Modifying the path class member of the path string (for example, changeextension) does not affect the file name in the file system. However, the path member does verify the content of the specified path string. If the string contains invalid characters in the path string (such as the definition in invalidpathchars), argumentexception is thrown. For example, on a Windows-based desktop platform, invalid path characters may include quotation marks ("), less than signs (<), greater than signs (>), and pipe symbols (|), return (\ B), empty (\ 0), and Unicode characters from 16 to 18 and from 20 to 25.
The members of the path class allow you to quickly and conveniently perform common operations, such as determining whether the file extension is part of a path and combining two strings into a path name.
In most cases, an exception is thrown if these methods receive invalid paths, but if the path name contains wildcards (* Or ?) Otherwise, no exception is thrown (you can use the getinvalidpathchars method to obtain invalid path characters ). We can determine whether a path is valid based on this principle.
Ii. Related General file dialog box
1. Folder browsing dialog box (folderbrowserdialog class)
In this dialog box, you can browse, create, and select a folder.
Main attributes:
Description: The description text displayed on the Tree View control. For example, select the directory to be calculated ";
Rootfolder: gets or sets the root folder from which browsing starts, for example, my computer (desktop by default) set in );
Selectedpath: gets or sets the path selected by the user. If this attribute is set, the specified path is located in the dialog box, which is the root folder by default, when the dialog box is closed, the path selected by the user is obtained based on this attribute;
Shownewfolderbutton: Get or set whether to display the new dialog box button;
Main Methods:
Showdialog: In this dialog box, the returned value is a dialogresult type value. If dialogresult. OK is returned, the selectedpath attribute can be used to obtain the path selected by the user;

Dlgopenfolder. Description = "select the directory for calculation ";
Dlgopenfolder. rootfolder = environment. specialfolder. mycomputer;
Dlgopenfolder. shownewfolderbutton = true;
Dialogresult result = dlgopenfolder. showdialog (this );
If (result = dialogresult. OK)
Txtdirpath. Text = dlgopenfolder. selectedpath;

2. open the file dialog box (openfiledialog class)
You can select an object in the dialog box.
Main attributes:
Checkfileexists: indicates whether the dialog box displays a warning if the user specifies a file name that does not exist;
Filename (s): gets or sets a string containing the selected file name in the file dialog box;
Filter: obtains or sets the list of file types in the dialog box;
Filterindex: Index of the file type list in the dialog box (based on 1 );
Initialdirectory: gets or sets the initial directory displayed in the file dialog box;
Multiselect: Indicates whether multiple files can be selected in the dialog box;
Showreadonly: indicates whether the dialog box contains the read-only check box;
Title: obtains or sets the title of the file dialog box;
Main Methods:
Openfile: open the file selected by the user with read-only permission;
Showdialog: Open the mode dialog box;

Dlgopenfile. Title = "open source file ";
Dlgopenfile. initialdirectory = @ "C: \ Inetpub \";
Dlgopenfile. Filter = "text file (*. txt) | *. txt | all files (*. *) | *.*";
Dlgopenfile. filterindex = 2;
Dlgopenfile. showreadonly = true;
Dialogresult DR = dlgopenfile. showdialog ();
If (DR = dialogresult. OK)
String filename = dlgopenfile. filename;

3. Save file dialog box (savefiledialog class)
You can save an object in this dialog box.
Main attributes:
Most of them are similar to opening a file dialog box, which is skipped here. The following are worth noting:
Createprompt: indicates whether the user is prompted to allow the user to create a file if the user specifies that the file does not exist;
Overwriteprompt: indicates whether the dialog box displays a warning if the specified file name already exists;
Main Methods:
Openfile: Open the selected file with read/write permissions;
Showdialog: Open the mode dialog box;
Sample Code:

Dlgsavefile. Title = "open target file ";
Dlgsavefile. initialdirectory = @ "C: \ Inetpub \";
Dlgsavefile. Filter = "text file (*. txt) | *. txt | all files (*. *) | *.*";
Dlgsavefile. filterindex = 2;
Dialogresult DR = dlgsavefile. showdialog ();
If (DR = dialogresult. OK)
String filename = dlgsavefile. filename;

At this point, we only operate on paths. You must know that these paths are only strings and do not involve real files in the file system.
3. file and directory operations
File and directory operations mainly involve the following classes: fileinfo, directoryinfo, and driveinfo. One of them can be considered to correspond to a file, directory, and drive. Their usage is similar. Generally, the file, directory, or drive path is passed as a parameter to the corresponding constructor to create an instance and then access their attributes and methods.
Note the following:
Both the fileinfo class and the directoryinfo class inherit from the abstract class filesysteminfo. The filesysteminfo class defines some common attributes, such as creationtime and exists. However, the driveinfo class does not inherit the filesysteminfo class, so it does not have the general attributes mentioned above.
The attribute values exposed by objects in the fileinfo and directoryinfo classes are the values obtained during the first query. If the file or directory is changed after this query, you must call their refresh method to update these attributes. Driveinfo does not need to do so. Its Attributes read the latest information of the file system each time.
When creating an instance of a file, directory, or drive, if a non-existent path is used, no error is reported. This is an object that represents an entity that does not exist, this means that the value of its exists attribute (isready attribute for driveinfo) is false. You can still operate on this object. However, if you try most other attributes, the corresponding filenotfoundexception, directorynotfoundexception, or drivenotfoundexception exception will be thrown.
In addition, you can also use the file/Directory class. The members of both classes are static methods. Therefore, if you only want to execute one operation, the efficiency of using static methods in file/directory is higher than that of using the instance methods in the corresponding fileinfo/directoryinfo. All file/directory methods require the path of the file/directory currently operated. Note: static methods of the file/Directory class perform security checks on all methods. If you want to reuse an object multiple times, you can use the corresponding instance method of fileinfo/directoryinfo, because security check is not always required.
The following are some common problems:
Question 1: How to obtain the basic information of a specified file;
Solution: You can use the attributes of the fileinfo class:
Fileinfo. exists: obtains whether the specified file exists;
Fileinfo. Name, fileinfo. extensioin: get the file name and extension;
Fileinfo. fullname: Get the full-qualified name of the file (full path );
Fileinfo. Directory: directory where the file is located. The returned type is directoryinfo;
Fileinfo. directoryname: Obtain the path of the directory where the file is located (full path );
Fileinfo. Length: get the file size (number of bytes );
Fileinfo. isreadonly: Gets whether the file is read-only;
Fileinfo. attributes: gets or sets the attributes of a specified file. The returned type is fileattributes enumeration. It can be a combination of multiple values (see question 2 );
Fileinfo. creationtime, fileinfo. lastaccesstime, and fileinfo. lastwritetime are used to obtain the file creation time, access time, and modification time respectively;
(For more information, see msdn)
Question 2: How to obtain and set file attributes, such as read-only, archive, and hide;
Use fileinfo. the attributes attribute can be used to obtain and set the attributes of a file. The attribute type is fileattributes enumeration. Each value of this enumeration represents an attribute. The fileattributes enumeration has the attribute flagsattribute, therefore, the enumerated values can be combined, that is, a file can have multiple attributes at the same time. Let's take a look at the specific practices:
Obtain attributes, such as checking whether a file is read-only:

// This method fails when the file has other attributes.
If (file. Attributes = fileattributes. readonly)
Chkreadonly. Checked = true;
// This method won't be a problem. It only checks read-only attributes.
If (file. Attributes & fileattributes. readonly) = fileattributes. readonly)
Chkreadonly. Checked = true;

Set attributes, such as adding and removing read-only attributes of a file:

If (chkreadonly. Checked)
// Add read-only attributes
File. Attributes | = fileattributes. readonly;
// Remove the read-only attribute
File. Attributes & = ~ Fileattributes. readonly;

Question 3: How to obtain the file version information (such as the version number, copyright statement, and company name );
Use the fileversioninfo class, which has a large number of version information-related attributes. The static method getversioninfo is used to obtain an instance of the class, and then you can access the version information of the specified file, which is very convenient. For example, fileversion indicates the file version number, legalcopyright indicates the copyright statement of the specified file, and companyName indicates the company name of the specified file. (For more information, see msdn)
Question 4: how to determine whether the content of the two files is the same (exact match );
Use the system. Security. cryptography. hashalgorithm class to generate a hash code for each file, and then compare whether the two hash codes are consistent.
You can use several methods to compare the file content. For example, check whether a specific part of the file is consistent. If you want to, you can even read the file byte and compare it by byte. Both methods are acceptable, but in some cases, it is more convenient to use the hash algorithm.
This algorithm generates a small (usually about 20 bytes) binary "fingerprint" (Binary fingerprint) for a file ). From a statistical perspective, different files cannot generate the same hash code. In fact, even a small change (such as modifying a bit in the source file) has a 50% chance to change every bit in the hash code. Therefore, hash codes are often used for data security.
To generate a hash code, you must first create a hashalgorithm object, which usually calls hashalgorithm. and then call hashalgorithm. the computehash method returns an array of bytes that store the hash code. The Code is as follows:

/// <Summary>
/// Determine whether the content of the two files is consistent
/// </Summary>
Public static bool isfilesequal (string filename1, string filename2)
Using (hashalgorithm hashalg = hashalgorithm. Create ())
Using (filestream fs1 = new filestream (filename1, filemode. Open), fs2 = new filestream (filename2, filemode. Open ))
Byte [] hashbytes1 = hashalg. computehash (fs1 );
Byte [] hashbytes2 = hashalg. computehash (fs2 );
// Compare the hash code
Return (bitconverter. tostring (hashbytes1) = bitconverter. tostring (hashbytes2 ));

Question 5: How to obtain the basic information of a specified directory;
Solution: You can use the relevant attributes and methods of the directoryinfo class:
Directoryinfo. exists: Gets whether the specified directory exists;
Directoryinfo. Name: Get the directory name;
Directoryinfo. fullname: Get the fully qualified directory name (full path );
Directoryinfo. attributes: gets or sets the attribute of the specified directory. The returned type is fileattributes enumeration, which can be a combination of multiple values;
Directoryinfo. creationtime, fileinfo. lastaccesstime, and fileinfo. lastwritetime are used to obtain the Directory Creation Time, access time, and modification time respectively;
Directoryinfo. Parent: gets the parent directory of the directory. The returned type is directoryinfo;
Directoryinfo. Root: Get the root directory of the directory. The return type is directoryinfo;
Question 6: how to obtain files and subdirectories contained in a specified directory;
Directoryinfo. getfiles (): gets the files in the directory (excluding subdirectories). The returned type is fileinfo []. Wildcards are supported;
Directoryinfo. getdirectories (): gets the subdirectories of a directory (excluding subdirectories,
The return type is directoryinfo []. wildcard search is supported;
Directoryinfo. getfilesysteminfos (): obtains files and subdirectories in a specified directory (excluding subdirectories,
The return type is filesysteminfo []. wildcard search is supported;
Question 7: how to obtain the size of a specified directory;
Check all the files in the directory, use the fileinfo. Length attribute to get the size of each file, aggregate the files, and use recursive algorithms to process all the files in the subdirectories. refer to the following code:

/// <Summary>
/// Calculate the size of a directory
/// </Summary>
/// <Param name = "Di"> specify a directory </param>
/// <Param name = "includesubdir"> include sub-directories </param>
/// <Returns> </returns>
Private long calculatedirsize (directoryinfo Di, bool includesubdir)
Long totalsize = 0;
// Check all (direct) contained files
Fileinfo [] files = Di. getfiles ();
Foreach (fileinfo file in files)
Totalsize + = file. length;
// Check all subdirectories. If the includesubdir parameter is true
If (includesubdir)
Directoryinfo [] dirs = Di. getdirectories ();
Foreach (directoryinfo dir in dirs)
Totalsize + = calculatedirsize (Dir, includesubdir );
Return totalsize;

Question 8: how to use wildcards to search for all objects in a specified directory;
Use the reload version of The directoryinfo. getfiles method. It can accept a filter expression and return the fileinfo array. In addition, its parameter can also specify whether to search for subdirectories. For example:
Dir. getfiles ("*. txt", searchoption. alldirectories );
Question 9: how to copy, move, rename, and delete files and directories;
Solution: Use the fileinfo and directoryinfo classes.
The following describes how to use the fileinfo class:
Fileinfo. copyto: Copies an existing file to a new file. Its overloaded version can overwrite existing files;
Fileinfo. moveTo: Move the specified file to a new location and provide the option to specify a new file name. Therefore, it can be used to rename the file (without changing the location); fileinfo. delete: Permanently deletes an object. If the object does not exist, no operation is performed;
Fileinfo. Replace: Replace the target file with the content of the file corresponding to the current fileinfo object, and specify another file name as the backup of the replaced file. Microsoft is considerate.
The following describes how to use the directoryinfo class:
Directoryinfo. Create: Create a specified directory. If multiple levels of directories do not exist in the specified path, this method is created one by one;
Directoryinfo. createsubdirectory: Create a subdirectory of the Directory corresponding to the current object;
Directoryinfo. moveTo: Move the directory (and its contents) to a new directory. You can also rename the directory;
Directoryinfo. Delete: delete a directory (if it exists ). If you want to delete a directory that contains subdirectories, you need to use its overloaded version to specify recursive deletion.
Did you notice? The directoryinfo class lacks a copyto method, but we can implement this function through recursion:

/// <Summary>
/// Copy the directory to the target directory
/// </Summary>
/// <Param name = "Source"> source directory </param>
/// <Param name = "destination"> target directory </param>
Public static void copydirectory (directoryinfo source, directoryinfo destination)
// If the two directories are the same, you do not need to copy them.
If (destination. fullname. Equals (source. fullname ))
// If the target directory does not exist, create it
If (! Destination. exists)
Destination. Create ();
// Copy all objects
Fileinfo [] files = source. getfiles ();
Foreach (fileinfo file in files)
// Copy the file to the target directory
File. copyto (path. Combine (destination. fullname, file. Name), true );
// Process Sub-Directories
Directoryinfo [] dirs = source. getdirectories ();
Foreach (directoryinfo dir in dirs)
String destinationdir = path. Combine (destination. fullname, dir. Name );
// Recursive processing subdirectory
Copydirectory (Dir, new directoryinfo (destinationdir ));

Question 10: how to obtain all logical drives of a computer;
Solution: Use the driveinfo class (. NET 2.0 is required)
Driveinfo. getdrives (): obtains all logical drives of the computer. The return type is driveinfo [];
Question 11: how to obtain the information of a specified drive;
Driveinfo. Name: get the drive name (for example, c :\);
Driveinfo. drivetype: obtains the drive type (such as fixed, CDROM, removable, and network );
Driveinfo. driveformat: get the drive format (such as NTFS, FAT32, CDFs, UDF, etc );
Driveinfo. isready: Get whether the drive is ready, for example, whether the CD is in the CD drive. If the drive is not ready, access to its information will cause an ioexception type exception;
Driveinfo. availablefreespace: obtains the available space of the drive;
Driveinfo. totalfreespace: gets the total available space of the drive. Unlike availablefreespace, availablefreespace sets the disk quota;
Driveinfo. totalsize: obtains the total space of the drive;
Driveinfo. rootdirectory: Get the root directory of the drive (directoryinfo type );
Now, we have learned some basic operations related to files and directories.


From http://blog.163.com/wwxwb_913/blog/static/97685362010621112545464? Fromdm & fromsearch & isfromsearchengine = Yes

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.