paths, files, directories, I/O Common operations Summary

Source: Internet
Author: User
Tags instance method save file

A

Summary:
File manipulation is a very basic and important part of the program, while paths, files, directories, and I/O are common themes in file operations, here's a summary of these common issues, and try to provide solutions to every problem, even without the answers you want, and hopefully provide you with some helpful 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 merged path, the system folder path and so on;
The related Common file dialog box, these dialog boxes can help us to operate the file system files and directories;
Iii. files, directories, drive operations, such as obtaining basic information about them, getting and setting properties of files and directories, file version information,
Search files and directories, file a sentence, copy, move, delete, rename files and directories;
Read and write files, including temporary files, random file names, etc.;
V. Monitoring of the file system;
The first two parts are written in this article.

a path-related operation
Question 1: How to determine whether a given path is valid/valid;
Solution: Get the 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, the use of directory.exists or File.exist method, if the former is true, the path represents the directory, if the latter is true, the path represents the file;
2, the above method has a disadvantage is not to deal with those non-existent files or directories. At this point you can consider using the Path.getfilename method to obtain
The file name it contains, if a path is not empty, and the file name is empty then it represents the directory, otherwise the file is represented;

Question 3: How to get a specific part of the path (such as filename, extension, etc.);
Solution:
Here are a few related methods:
Path.getdirectoryname: Returns the directory information for the specified path string;
Path.getextension: Returns the extension of the specified path string;
Path.getfilename: Returns the filename and extension of the specified path string;
Path.getfilenamewithoutextension: Returns the filename of a path string that does not have an extension;
Path.getpathroot: Gets the root directory information of the specified path;
(Please also refer to MSDN for more information)

Question 4: How to merge two paths accurately without worrying about that annoying "/" character;
Solution:
Using the Path.Combine method, it will help you deal with annoying "/";

2, open the File dialog box (OpenFileDialog Class)
The dialog box allows users to select a file, as shown in the following figure:

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 file name 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: This value indicates whether the dialog box allows multiple files to be selected;
ShowReadOnly: This value indicates whether the dialog box contains a read-only check box;
Title: Gets or sets the file dialog box caption;
Main methods:
OpenFile: Opens a user-selected file with read-only access;
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)
Users can save a file through this dialog box, as shown in the following figure:

Main properties:
Most of these are similar to the Open File dialog box, which is skipped here, and the following are notable:
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: Opens a user-selected file with read/write permissions;
ShowDialog: Open the modal 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;
}

Two

Summary:
File manipulation is a very basic and important part of the program, while paths, files, directories, and I/O are common themes in file operations, here's a summary of these common issues, and try to provide solutions to every problem, even without the answers you want, and hopefully provide you with some helpful 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 merged path, the system folder path and so on;
The related Common file dialog box, these dialog boxes can help us to operate the file system files and directories;
Iii. files, directories, drive operations, such as obtaining basic information about them, getting and setting properties of files and directories, file version information,
Search files and directories, file a sentence, copy, move, delete, rename files and directories;
Read and write files, including temporary files, random file names, etc.;
V. Monitoring of the file system;

The last article introduces the first to second part, which introduces the most important part of the third section.

Third, file and directory-related operations
The classes involved in file and directory operations are mainly: Fileinfo,directoryinfo,driveinfo, which can be thought to correspond to a single instance of a file, directory, and drive. They are similar in usage, typically by passing the path of a file, directory, or drive as a parameter 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. However, the DriveInfo class does not inherit the FileSystemInfo class, so it does not have the common properties mentioned above.

Objects of the FileInfo class and the DirectoryInfo class expose property values that are obtained when the first query is made, and they must be updated by calling their Refresh method if the file or directory changes after the query is taken. But DriveInfo does not need to do this, and its properties read the latest information about the file system every time.

When you create an instance of a file, directory, or drive, if you use a path that does not exist, and you do not make an error, you get an object that represents an entity that does not exist, which means that its Exists property (the IsReady attribute for DriveInfo) is false. You can still manipulate the entity, but if you try most of the other properties, it raises the corresponding FileNotFoundException, directorynotfoundexception, or Drivenotfoundexception exception.

    Alternatively, you can use the File/directory class, where the members of these two classes are static methods, so if you want to perform only one operation, then the efficiency of using static methods in File/directory is more efficient than using the corresponding FileInfo The instance method in/DirectoryInfo may be higher. All file/directory methods require the path of the file/directory that is currently being manipulated. Note: The static methods of the File/directory class perform security checks on all methods. If you plan to reuse an object multiple times, consider using the appropriate instance method for 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 a FileAttributes enumeration, and can be a combination of multiple values (see question 2);
Fileinfo.creationtime, Fileinfo.lastaccesstime, Fileinfo.lastwritetime: To obtain the file creation time, access time, modification time respectively;
(Please also refer to MSDN for more information)

Question 2: How to Get and set the properties of a 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, where each value represents a property, and the FileAttributes enumeration has attributes FlagsAttribute, so The value of this 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;
}

This is not a problem, it only checks read-only properties
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, this class has a large number of version-related properties. It is convenient to obtain an instance of the class by its static method and then access the version information of the specified file (getversioninfo). If FileVersion represents the file version number, Legalcopyright represents the copyright notice for the specified file, CompanyName represents the company name of the specified file. (Please also refer to MSDN for more information)

    4: How to tell if 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 two hash codes for consistency.
    can use several methods when comparing the contents of a file. For example, check to see if a particular part of a file is consistent, and if so, 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 a hash code algorithm.
    The algorithm generates a small (usually approximately 20-byte) binary "fingerprint" (binary fingerprint) for a file. Statistically, it is not possible for different files to generate the same hash code. In fact, even a small change, such as modifying a bit in the source file, would have a 50% chance of changing every bit in the hash code. Therefore, hash codes are often used in 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 by 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

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.