File operations are very basic and important in the program, and the path, files, directories and I/O are common topics in the file operation, here want to summarize these common problems, for each problem, as far as possible to provide some solutions, even if there is no answer you want, but also hope to provide you with a bit of useful ideas, If you have good suggestions, please be able to leave a message to make these content more perfect.
Main content:
The related operation of the path, such as determining whether the path is legitimate, the path type, the specific part of the path, the merge path, the system folder path and so on;
Second, the relevant common file dialog box, these dialog boxes can help us to manipulate files and directories in the file system;
Third, file, directory, drive operation, such as get their basic information, get and set the file and directory properties, file version information,
Search for files and directories, file judgments, etc., copy, move, delete, rename files and directories;
Iv. read and write files, including temporary files, random file names, etc.;
V. Monitoring of the file system;
The first two parts of this article are written.
One, path-related operations
Question 1: How to determine if a given path is valid/legal;
Solution: Obtain an illegal path/file name character by Path.getinvalidpathchars or Path.getinvalidfilenamechars method, you can
According to it to determine whether the path contains illegal characters;
Question 2: How to determine whether a path string represents a directory or a file;
Solution:
1, using the Directory.Exists or File.exist method, if the former is true, then the path represents the directory, if the latter is true, then the path represents the file;
2, the above method has a disadvantage is not to handle those files or directories that do not exist. Consider using the Path.getfilename method to obtain
It contains the file name, if a path is not empty, and the file name is empty then it represents the directory, otherwise represents the file;
Question 3: How to obtain a specific part of the path (such as file name, extension, etc.);
Solution:
Here are a few related methods:
Path.getdirectoryname: Returns directory information for the specified path string;
Path.getextension: Returns the extension of the specified path string;
Path.getfilename: Returns the file name and extension of the specified path string;
Path.getfilenamewithoutextension: Returns the file name of a path string that does not have an extension;
Path.getpathroot: Gets the root directory information for the specified path;
(See also MSDN for more information)
Question 4: How to accurately merge two paths without worrying about the annoying "\" character;
Solution:
Using the Path.Combine method, it will help you deal with annoying "\";
Question 5: How to get the path of the system directory (such as desktop, My Documents, temp folder, etc.);
Solution:
The main use is system. Related properties and methods of the Environment class:
Environment. Systemdirectory property: Gets the fully qualified path of the system directory;
Environment. GetFolderPath method: The method accepts a parameter type of Environment.SpecialFolder enumeration,
Through this method can obtain a large number of system folder path, such as My computer, my Computer, desktop, system directory, etc.;
(See also MSDN for more information);
Path.gettemppath method: Returns the path of the temporary folder of the current system;
Question 6: How to determine whether a path is an absolute path or a relative path;
Solution:
Using the Path.ispathrooted method;
Question 7: How to read or set the current directory;
Solution:
Use the GetCurrentDirectory and SetCurrentDirectory methods of the directory class;
Question 8: How to use relative paths;
Solution:
After setting the current directory (see question 7), you can use a relative path. For a relative path, we can
Use the Path.GetFullPath method to get its fully qualified path (absolute path).
Note: If you intend to use relative paths, it is recommended that you set the working directory as a common starting point for each interactive file, or you might introduce
Some difficult to find security risks, by malicious users to access system files.
More content:
Usually we can use the System.IO.Path class to handle the path. This class provides a set of methods and properties to perform operations on strings that contain file or directory path information, which are performed in a cross-platform manner, and these methods and properties are static.
Note that the path is simply a string that provides the location of the file or directory. The path does not have to point to a location on the disk, for example, the path can be mapped to an in-memory or location on the device. The exact format of the path is determined by the current platform. For example, on some systems, a path can start with a drive letter or a volume number, and this element does not exist in other systems. On some systems, the file path can contain an extension that indicates the type of information stored in the file. The format of the file name extension is platform-dependent, for example, some systems limit the length of the extension to 3 characters, while other systems do not. The current platform also determines the character set used to separate elements in the path, and the character set that cannot be used when specifying a path. Because of these differences, the exact behavior of the fields of the path class and some members of the path class is platform-dependent.
The path can contain absolute or relative location information. Absolute path complete Specifies a location: The file or directory can be uniquely identified, regardless of the current location. Relative paths Specify a partial location: The current position is used as the starting point when locating a file specified with a relative path.
Most members of the path class do not interact with the file system and do not verify that the file specified by the path string exists. The path class member (for example, changeextension) that modifies the route string has no effect on the file name in the file system. However, the path member does validate the contents of the specified path string, and if the string contains characters that are not valid in the path string, such as defined in InvalidPathChars, the ArgumentException exception is thrown. For example, on a Windows-based desktop platform, invalid path characters might include quotation marks ("), less than sign (<), greater than sign (>), pipe symbol (|), backspace (\b), empty (+), and Unicode characters from 16 to 18 and from 20 to 25.
Members of the path class enable you to perform common operations quickly and easily, such as determining whether a file extension is part of a path, and combining two strings into a pathname.
In most cases, an exception is thrown if these methods receive an invalid path, but if the pathname is invalid because it contains a wildcard character (* or?), no exception is thrown (you can use the Getinvalidpathchars method to illegal path characters). We can judge whether a path is legal according to this principle.
Second, the relevant common file dialog box
1. Folder browse dialog box (FolderBrowserDialog Class)
The dialog box allows users to browse, create, and select folders
Main properties:
Description: The description text that is displayed on the TreeView control, such as "Select the directory to be evaluated" in;
RootFolder: Gets or sets the root folder from which to start browsing, as set in My Computer (default to desktop);
SelectedPath: Gets or sets the path selected by the user, if the property is set, the dialog box is opened to the specified path, the default is the root folder, and when the dialog box is closed, the path selected by the user user is obtained;
Shownewfolderbutton: Gets or sets whether the New dialog box button is displayed;
Main methods:
ShowDialog: Opens the dialog box, returns a value of type DialogResult, and, if DialogResult.OK, gets the path selected by the user by the SelectedPath property;
dlgopenfolder.description = "Select the directory to be computed";
Dlgopenfolder.rootfolder = Environment.SpecialFolder.MyComputer;
Dlgopenfolder.shownewfolderbutton = true;
DialogResult result = Dlgopenfolder.showdialog (this);
if (result = = DialogResult.OK)
{
Txtdirpath.text = Dlgopenfolder.selectedpath;
}
2, Open File dialog box (OpenFileDialog Class)
User can select a file from this dialog
Main properties:
Checkfileexists: This value 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 filename selected in the file dialog box;
Filter: Gets or sets the list of file types for the dialog box;
FilterIndex: The index of the file type List of the dialog box (based on 1);
InitialDirectory: Gets or sets the initial directory displayed by the file dialog box;
MultiSelect: Indicates whether the dialog box allows multiple files to be selected;
ShowReadOnly: Indicates whether the dialog box contains a read-only check box;
Title: Gets or sets the file dialog title;
Main method:
OpenFile: Open the file with read-only permission selected by the user;
ShowDialog: Open the modal 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)
The dialog box allows the user to save a file
Main properties:
Most are similar to the Open File dialog box, which is skipped here, and the following are noteworthy:
Createprompt: This value indicates whether the user is prompted to allow the file to be created if the user specifies a file that does not exist;
Overwriteprompt: This value indicates whether the dialog box displays a warning if the user-specified file name already exists;
Main methods:
OpenFile: Open a user-selected file with read/write permission;
ShowDialog: Opens the modal dialog box;
Example 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, all we do is just the path, knowing that these paths are just strings, not yet related to the real files in the filesystem.
Iii. file and directory-related operations
The classes involved in file and directory operations are mainly: Fileinfo,directoryinfo,driveinfo, which can be thought of as one instance of a file, directory, drive. They are used in a similar way, typically by passing the path of a file, directory, or drive as an argument to the appropriate constructor to create an instance, and then accessing their properties and methods.
Note the following points:
Both the FileInfo class and the DirectoryInfo class inherit from the abstract class FileSystemInfo, and the FileSystemInfo class defines some common properties, such as CreationTime, Exists, and so on. But the DriveInfo class does not inherit the FileSystemInfo class, so it does not have the generic properties mentioned above.
The property values exposed by the objects of the FileInfo class and the DirectoryInfo class are the values obtained at the first query, and if the files or directories are changed after the query, they must be updated by calling their refresh methods. However, DriveInfo does not need to do this, and its properties will read the latest information about the file system every time.
When you create an instance of a file, directory, or drive, and you use a nonexistent path without an error, you get an object that represents an entity that does not exist, which means that its Exists property (the IsReady property for DriveInfo) has a value of false. You can still manipulate the entity, but if you try most of the other properties, the corresponding FileNotFoundException, directorynotfoundexception, or Drivenotfoundexception exception will be thrown.
In addition, you can use the File/directory class, where members of the two classes are static methods, so if you want to perform only one operation, then using the static method in File/directory is more efficient than using the corresponding Fileinfo/directoryinfo Instance methods may be higher. All file/directory methods require the path of the file/directory that is currently being manipulated. Note: Static methods of the File/directory class perform security checks on all methods. If you intend to reuse an object multiple times, consider using the corresponding instance method of Fileinfo/directoryinfo, because security checks are not always required.
Here are some common questions:
Question 1: How to obtain the basic information of the specified file;
Solution: You can use the related properties of the FileInfo class:
Fileinfo.exists: Gets whether the specified file exists;
Fileinfo.name,fileinfo.extensioin: Gets the name and extension of the file;
Fileinfo.fullname: Gets the fully qualified name of the file (full path);
Fileinfo.directory: Gets the directory where the file is located, the return type is DirectoryInfo;
Fileinfo.directoryname: Gets the path to the directory where the file resides (full path);
Fileinfo.length: Gets the size of the file (in bytes);
Fileinfo.isreadonly: Gets whether the file is read-only;
Fileinfo.attributes: Gets or sets the properties of the specified file, the return type is the FileAttributes enumeration, which can be a combination of multiple values (see question 2);
Fileinfo.creationtime, Fileinfo.lastaccesstime, Fileinfo.lastwritetime: respectively, to obtain the file creation time, access time, modification time;
(See also MSDN for more information)
Question 2: How to Get and set the properties of the file, such as read-only, archive, hide, etc.;
Solution:
You can use the Fileinfo.attributes property to get and set the properties of a file, which is a FileAttributes enumeration, each value of that enumeration represents an attribute, FileAttributes enumeration has a property (Attribute) FlagsAttribute, so The value of the enumeration can be combined, that is, a file can have multiple properties at the same time. Here's a look at the specific approach:
Gets a property, such as determining whether a file is read-only:
This behavior fails when the file has other properties
if (file. Attributes = = fileattributes.readonly)
{
Chkreadonly.checked = true;
}
There is no problem with this notation, it only checks the read-only property
if (file. Attributes & fileattributes.readonly) = = fileattributes.readonly)
{
Chkreadonly.checked = true;
}
Set properties, such as adding and removing read-only properties for a file:
if (chkreadonly.checked)
{
// Add read-only property
file. Attributes |= fileattributes.readonly;
}
Else
{
//Remove read-only properties
file. Attributes &= ~fileattributes.readonly;
}
Question 3: How to obtain the version information of the file (such as version number, copyright notice, company name, etc.);
Solution:
Using the FileVersionInfo class, the class has a large number of version information-related properties. It is convenient to obtain an instance of the class through its static method, and then to access the version information of the specified file (getversioninfo). If FileVersion represents a file version number, Legalcopyright represents the copyright notice for the specified file, CompanyName represents the company name of the specified file. (See also MSDN for more information)
Question 4: How to determine whether the contents of two files are the same (exact match);
Solution:
Use the System.security.Cryptography.HashAlgorithm class to generate a hash code for each file, and then compare the two hash codes for consistency.
There are several ways to compare the contents of a file. For example, check whether a particular part of a file is consistent, and if you prefer, you can even read the file byte-by-byte to compare it. Both of these methods are possible, but in some cases, it is more convenient to use the hash code algorithm.
The algorithm generates a small (usually about 20 bytes) binary "fingerprint" (binary fingerprint) for a file. Statistically, different files cannot generate the same hash code. In fact, even a small change (for example, a bit in the source file) would have a 50% chance of changing each 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, This is usually done by calling the Hashalgorithm.create method, and then calling the Hashalgorithm.computehash method, which returns a byte array that stores the hash code. The code is as follows:
<summary>
Determine if the contents of two files are 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 hash Codes
Return (bitconverter.tostring (hashBytes1) = = bitconverter.tostring (hashBytes2));
}
}
}
Question 5: How to obtain the basic information of the specified directory;
Solution: You can use the related properties and methods of the DirectoryInfo class:
Directoryinfo.exists: Gets whether the specified directory exists;
Directoryinfo.name: Gets the name of the directory;
Directoryinfo.fullname: Gets the fully qualified name of the directory (full path);
Directoryinfo.attributes: Gets or sets the property of the specified directory, the return type is the FileAttributes enumeration, which can be a combination of multiple values;
Directoryinfo.creationtime, Fileinfo.lastaccesstime, Fileinfo.lastwritetime: respectively, to obtain the creation time of the directory, Access time, modification time;
Directoryinfo.parent: Gets the parent directory of the directory, the return type is DirectoryInfo;
Directoryinfo.root: Gets the root directory of the directory, the return type is DirectoryInfo;
Question 6: How to get the files and subdirectories contained in the specified directory;
Solution:
Directoryinfo.getfiles (): Gets the file in the directory (does not contain subdirectories), the return type is fileinfo[], and supports wildcard lookup;
Directoryinfo.getdirectories (): Gets a subdirectory of the directory (without subdirectories),
The return type is directoryinfo[], and wildcard lookup is supported;
DirectoryInfo. Getfilesysteminfos (): Gets the files and subdirectories under the specified directory (not including subdirectories).
The return type is filesysteminfo[], and wildcard lookup is supported;
Question 7: How to obtain the size of the specified directory;
Solution:
Check all the files in the directory, take advantage of the Fileinfo.length property to get the size of each file, then make a total, and then use the recursive algorithm to process all subdirectories of the file, refer to the following code:
<summary>
Calculate the size of a directory
</summary>
<param name= "di" > Specified directory </param>
<param name= "Includesubdir" > whether to include subdirectories </param>
<returns></returns>
Private Long Calculatedirsize (DirectoryInfo di, bool Includesubdir)
{
Long totalsize = 0;
Check all (directly) included 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 all files in a specified directory;
Solution:
Using the overloaded version of the Directoryinfo.getfiles method, it can accept a filter expression, return an array of FileInfo, and its parameters can also specify whether to find subdirectories. Such as:
Dir. GetFiles ("*.txt", searchoption.alldirectories);
Question 9: How to copy, move, rename, delete files and directories;
Solution: Use the FileInfo and DirectoryInfo classes.
The following are the related methods of the FileInfo class:
Fileinfo.copyto: Copy an existing file to a new file, and its overloaded version also allows overwriting a file that already exists;
Fileinfo.moveto: Moves the specified file to the new location and provides the option to specify a new file name, so it can be used to rename the file (without changing the location); Fileinfo.delete: Permanently delete the file, if the file does not exist, do nothing;
Fileinfo.replace: Microsoft considers it thoughtful to replace the target file with the contents of the current FileInfo object, and to designate another file name as a backup of the replaced file.
The following are the related methods of the DirectoryInfo class:
Directoryinfo.create: Creates the specified directory, which is created if there are multiple levels of directories in the specified path that do not exist;
Directoryinfo.createsubdirectory: Creates a subdirectory of the directory corresponding to the current object;
Directoryinfo.moveto: To move a directory (and its contents) to a new directory, or to rename a directory;
Directoryinfo.delete: Deletes the directory (if it exists). If you want to delete a directory that contains subdirectories, use the overloaded version of it to specify recursive deletions.
Did you notice it? The DirectoryInfo class is less of a CopyTo method, but we can implement this function by recursion:
<summary>
Copy Directory to destination directory
</summary>
<param name= "source" > Sources directory </param>
<param name= "Destination" > Target directory </param>
public static void CopyDirectory (DirectoryInfo source, DirectoryInfo destination)
{
If two directories are the same, you do not need to copy
if (destination. Fullname.equals (source. FullName))
{
Return
}
If the destination directory does not exist, create it
if (!destination. Exists)
{
Destination. Create ();
}
Copy all Files
fileinfo[] files = source. GetFiles ();
foreach (FileInfo file in files)
{
Copy the file to the destination directory
File. CopyTo (Path.Combine (destination. FullName, file. Name), true);
}
Working with sub-directories
directoryinfo[] dirs = source. GetDirectories ();
foreach (DirectoryInfo dir in dirs)
{
String destinationdir = Path.Combine (destination. FullName, dir. Name);
Recursively processing subdirectories
CopyDirectory (dir, New DirectoryInfo (Destinationdir));
}
}
Question 10: How to obtain all logical drives of the computer;
Solution: Use the DriveInfo class (requires. NET 2.0)
Driveinfo.getdrives (): Obtains all logical drives of the computer, the return type is driveinfo[];
Question 11: How to obtain information about the specified drive;
Solution:
Driveinfo.name: Gets the name of the drive (for example, \ n);
Driveinfo.drivetype: Gets the type of drive (e.g. fixed,cdrom,removable,network, etc.);
Driveinfo.driveformat: Get the format of the drive (e.g. NTFS,FAT32,CDFS,UDF, etc.);
Driveinfo.isready: Gets whether the drive is ready, such as whether the CD has been put into the CD drive, and if the drive is not ready, access to its information will cause a IOException type exception;
Driveinfo.availablefreespace: Gets the free space of the drive;
Driveinfo.totalfreespace: Gets the total free space of the drive, which differs from the availablefreespace in that the Availablefreespace disk quota is set;
Driveinfo.totalsize: Gets the total space of the drive;
Driveinfo.rootdirectory: Gets the root directory of the drive (DirectoryInfo type);
So far, we've learned some basic things about file and directory.
This article transferred from: http://blog.163.com/wwxwb_913/blog/static/97685362010621112545464/
C # Path/File/directory/I/O Common Operations Summary