C # Basic Knowledge Series-14 IO articles File operations (3)

Posted May 28, 20207 min read

This article continues the previous two articles and introduces you to the main methods and properties of the Path class and FileSystemInfo class.

As mentioned above, after the content related to the files in "C # Basic Knowledge Series-IO" is completed, we will lead you to develop a small tool-quickly retrieve the directory where the files are located.

1.3. Path

The Chinese name of Path has the meaning of path, so the Path class is the path class. C # sets Path as a tool class, and the instances of the path are divided into files and directories. The following is its definition:

public static class Path

The path is a character string describing the location of files and directories. The path does not necessarily point to the hard disk. In other words, the path may not necessarily be a physical path or may be a virtual path or a network path. On different operating systems and platforms, paths have different performances, so the Path class is a unified abstraction of the behavior of different platforms. The specific path representation needs to refer to the specific system representation form.

So let's first take a look at what Path provides for us, let us glance at a glance:

1.3.1 Field

public static readonly char AltDirectorySeparatorChar;
public static readonly char DirectorySeparatorChar;

These two are directory separators under a specific system, where AltDirectorySeparatorChar represents a forward slash(/) and DirectorySeparatorChar represents a backslash(). Why is it a directory separator under a specific system, because the Windows environment supports both separators, but Unix and Unix-like systems only support/as a directory separator. So if the system needs cross-platform support, it is best to use AltDirectorySeparatorChar as a directory separator.

public static readonly char PathSeparator;

This field returns the platform-specific separator that separates path strings in environment variables. Windows returns a semicolon(;), other platforms may behave differently.

public static readonly char VolumeSeparatorChar;

This represents the volume separator, which is a very interesting specific. For Linux systems, there is no volume similar to Windows, so this field will return a /, and in Windows, for example:

The D:Temp directory will return a colon(:).

1.3.2 Method

After introducing the fields, let's take a look at the methods that Path gives us.

Let's start with the most commonly used ones:

public static string Combine(params string []paths);
public static string Combine(string path1, string path2);
public static string Combine(string path1, string path2, string path3);
public static string Combine(string path1, string path2, string path3, string path4);

This group of methods is used to stitch paths. Except for the first parameter, each parameter should be a relative path relative to the previous parameter stitching result path. If an absolute path appears subsequently, the previously calculated path information will be discarded and recalculated.

The following is an example:

string []paths = {@ "d:\ archives", "2001", "media", "images"};
string fullPath = Path.Combine(paths);

paths = new string []{@ "d:\ archives \", @ "2001 \", "media", "images"};
fullPath = Path.Combine(paths);

paths = new string []{"d:/archives /", "2001 /", "media", "images"};
fullPath = Path.Combine(paths);
//Execution result under Windows system
//d:\ archives \ 2001 \ media \ images
//d:\ archives \ 2001 \ media \ images
//d:/archives/2001/media \ images
//Execution result of Unix-like system
//d:\ archives/2001/media/images
//d:\ archives \/2001 \/media/images

Continue to the next method:

public static string GetFullPath(string path, string basePath);
public static string GetFullPath(string path);

Get the absolute path of a relative path, where path is a relative path and basePath is an absolute path. If basePath is specified, the full path is calculated from basePath based on path.

public static string GetRelativePath(string relativeTo, string path);

Returns the relative path from one path to another, where relativeTo is the source path and path is the target path. Among them, relativeTo is always a directory, or is considered a directory.

public static string GetDirectoryName(string path);

Return the directory information in the path path, for example:"C:DirectorySubDirectorytest.txt", return "C:DirectorySubDirectory", if the path is a directory, then return the path string of its parent directory.

public static string Join(string path1, string path2, string path3, string path4);
public static string Join(string path1, string path2, string path3);
public static string Join(params string []paths);

Similar to the Combine method, but the Join method is to splice all the parameters according to the relative directory.

After talking about some operations of the directory, let's see what support Path provides for the file path:

public static string GetFileName(string path);

Get the file name in the path, for example:"C:mydirmyfile.ext", the return result is "myfile.ext", which means that this method will return the file name with the suffix name. Because the file name itself contains the suffix name.

public static string GetFileNameWithoutExtension(string path);

Returns the file name without the suffix name, similar to GetFileName, but it is not easy to include the file format suffix.

public static bool HasExtension(string path);

Determine whether to include the suffix name, also known as the format name or extension.

public static string GetExtension(string path);

Returns the suffix name of the file represented.

public static string ChangeExtension(string path, string extension);

Modify the file extension.

These are the commonly used methods of Path, everyone just has an impression.

1.3 FileSystemInfo

File system information, which is the base class of two classes of FileInfo and DirectoryInfo, which defines some attributes and methods common to files and directories in the file system. Let's take a brief look next.

First look at the declaration of the class:

public abstract class FileSystemInfo:MarshalByRefObject, System.Runtime.Serialization.ISerializable

An abstract class. This tag means that this class is an abstract class. Abstract classes cannot be instantiated directly, so we may not directly instantiate a FileSystemInfo ourselves.

So let's skip the constructor of FileSystemInfo and look directly at the properties and methods.

public System.IO.FileAttributes Attributes {get; set;}

Gets or sets the characteristics of the current file or directory. This characteristic is an enumeration, and it is a bit-marked enumeration type.

Name Value Meaning
Archive 32 This file is marked for inclusion in an incremental backup operation. Whenever a file is modified, Windows sets this attribute, and the backup software should clean up this attribute when processing the file during an incremental backup.
Compressed 2048 This file is a compressed file.
Device 64 Reserved for future use.
Directory 16 This file is a directory. Directory is supported on Windows, Linux and macOS.
Encrypted 16384 This file or directory is encrypted. For a file, it means that all data in the file is encrypted. For directories, it means that newly created files and directories are encrypted by default.
Hidden 2 The file is hidden, so it is not included in the normal directory listing. Hidden is supported on Windows, Linux and macOS.
IntegrityStream 32768 The file or directory includes integrity support data. When this value applies to a file, all data streams in the file have integrity support. When this value is applied to a directory, all new files and subdirectories should include integrity support in that directory and by default.
Normal 128 This file is a standard file with no special attributes. This feature is effective only when it is used alone. Normal is supported on Windows, Linux and macOS.
NoScrubData 131072 The file or directory is excluded from the integrity scan data. When this value is applied to a directory, all new files and subdirectories in that directory and by default should not include data integrity.
NotContentIndexed 8192 This file will not be indexed by the operating system's content indexing service.
Offline 4096 This file is offline and the file data is not immediately available for use.
ReadOnly 1 The file is read-only. ReadOnly is supported on Windows, Linux and macOS. On Linux and macOS, changing the ReadOnly flag is a permission operation.
ReparsePoint 1024 The file contains a reparse point, which is a user-defined data block associated with the file or directory. ReparsePoint is supported on Windows, Linux and macOS.
SparseFile 512 This file is a sparse file. Sparse files are generally large files with zero data.
System 4 This file is a system file. That is, the file is part of the operating system or is used exclusively by the operating system.
Temporary 256 The file is a temporary file. The temporary file contains data that is needed when the application is executed, but is not needed when the application is completed. The file system attempts to keep all data in memory instead of refreshing the data back to mass storage so that it can be accessed quickly. When the temporary file is no longer needed, the application should delete it immediately.

Judging by:

FileSystemInfo fsi;
bool isXXX =(fsi.Attributes & FileAttributes.XXX) == FileAttributes.XXX;

public DateTime CreationTime {get; set;}
public DateTime CreationTimeUtc {get; set;}

Returns the creation time of the file/directory, where UTC refers to Coordinated Universal Time.

public string Extension {get;}

Get the file suffix name(extension) of the file, with a period(.).

public virtual string FullName {get;}
public abstract string Name {get;}

Both return the name of the file or directory, but FullName returns the full path name, and Name only returns the file name.

public DateTime LastAccessTime {get; set;}
public DateTime LastAccessTimeUtc {get; set;}

Gets or sets the time of the file's last access. The return value of this attribute is not strictly the last access time, because some systems will not be updated in time.

public DateTime LastWriteTime {get; set;}
public DateTime LastWriteTimeUtc {get; set;}

The last modification time can be set or modified by yourself. Similar to LastAccessTime, it may not be the correct value.

2 . Summary

So far, the commonly used file API has been introduced. Next, we will demonstrate the use of various streams and the operation scenarios of various streams.

For more content, please pay attention to My Blog "Mr. Gao's Cabin"