C# I/O files and directories II: File and FileInfo

Table of contents

一.FileAccess

二.FileShare

3. FileMode

Four. FileOptions

Five. Similarities and differences between File and FileInfo

Six. Method

1.File

2.FileInfo 

Constructor

Attributes

method


Before understanding File and FileInfo, let's look at four enumerations

Note: The explanations of FileAccess/FileShare/FileMode/FileOptions are taken from https://learn.microsoft.com/zh-cn/dotnet/api/system.io.file?view=net-6.0

一.FileAccess

Specifies read and write access to the file.

Read      1     
Read access to the file. Data can be read from a file. Combined with Write for read and write access.


Write     2     
Write access to the file. Data can be written to a file. Combined with Read for read and write access.


ReadWrite     3     
Read and write access to the file. Data can be read from and written to files.

二.FileShare

Specifies the level of access allowed for used files.

None     0     
Declines to share the current file. Any request to open the file (by this process or another process) will fail until the file is closed.


Read      1     
allows the file to be subsequently opened for reading. If this flag is not specified, any request to open the file for reading (by this process or another process) will fail until the file is closed. However, even with this flag specified, additional permissions may be required to be able to access the file.


Write      2     
allows the file to be subsequently opened for writing. If this flag is not specified, any request to open the file for writing (by this process or another process) will fail until the file is closed. However, even with this flag specified, additional permissions may be required to be able to access the file.


ReadWrite     3     
allows the file to be subsequently opened for reading or writing. If this flag is not specified, any request (by this process or another process) to open the file for reading or writing will fail until the file is closed. However, even with this flag specified, additional permissions may be required to be able to access the file.


Delete     4     
allows subsequent deletion of files.


Inheritable      16     
enables file handles to be inherited by child processes. Win32 does not directly support this feature.


3. FileMode

Specifies whether the contents of existing files are preserved or overwritten, and whether requests to create existing files result in exceptions.

CreateNew     1     
specifies that the operating system should create a new file. This requires Write permission. If the file already exists, an IOException will be thrown.


Create     2     
specifies that the operating system should create the new file. If this file already exists, it will be overwritten. This requires Write permission. FileMode.Create is equivalent to a request to use CreateNew if the file does not exist; otherwise use Truncate. If the file already exists but is hidden, an UnauthorizedAccessException will be thrown.


Open      3     
specifies that the operating system should open the existing file. The ability to open a file depends on the value specified by the FileAccess enumeration. If the file does not exist, a FileNotFoundException is thrown.


OpenOrCreate     4     
specifies that the operating system should open the file if it exists; otherwise, a new file should be created. If the file is opened with FileAccess.Read, Read permission is required. If the file access is FileAccess.Write, Write permission is required. If the file is opened with FileAccess.ReadWrite, both Read and Write permissions are required.


Truncate      5     
specifies that the operating system should open the existing file. When the file is opened, it will be truncated to zero byte size. This requires Write permission. Attempting to read from a file opened with FileMode.Truncate will result in an ArgumentException.


Append     6     
If there is a file, open the file and find the end of the file, or create a new file. This requires the Append permission. FileMode.Append can only be used with FileAccess.Write. Attempts to seek past the end of the file throw an IOException, and any attempt to read fails with a NotSupportedException.

Four. FileOptions

Represents advanced options for creating a FileStream object.

None      0     
indicates that no other options should be used when generating the FileStream object.


Encrypted      16384     
indicates that the file is encrypted and can only be decrypted by the same user account used for encryption.


DeleteOnClose      67108864     
Instructs to automatically delete a file when it is no longer used.


SequentialScan      134217728     
indicates that files are accessed sequentially from beginning to end. The system can use this option as a hint to optimize file caching. If the application moves the file pointer for random access, optimized caching may not occur, but correctness of operation is still guaranteed. Performance can be improved in some cases if this flag is specified.


RandomAccess      268435456     
indicates random access to the file. The system can use this option as a hint to optimize file caching.


Asynchronous      1073741824     
indicates that the file is available for asynchronous reading and writing.


WriteThrough      -2147483648     
indicates that the system should write directly to disk, through any intermediate caches.

Five. Similarities and differences between File and FileInfo

1. Both File and FileInfo provide operations for files

2. File is a static class so all methods require the path of the file being processed

3.File can be used for multiple objects with different paths

4. Every time File is used, a security check is required

5. The constructor of FileInfo needs to pass in the path , so FileInfo can only be used for a single object (repeatable) , and does not always require security checks

Six. Method

Note: limited space only demonstrates some commonly used methods

1.File

Create(string path);
Create or overwrite files in the specified path.


Create(string path, int bufferSize);
Create or overwrite the specified file.


Create(string path, int bufferSize, FileOptions options);
Creates or overwrites the specified file, specifying the buffer size and a System.IO.FileOptions value describing how to create or overwrite the file.

public void CreateFile() {
        //创建或者覆盖文件
        using(FileStream fs = File.Create(path, 1024, FileOptions.Asynchronous)) {

        }
    }

Create(string path, int bufferSize, FileOptions options, FileSecurity fileSecurity);
Creates or overwrites the specified file with the specified buffer size, file options, and file security.


CreateText(String)     
creates or opens a file for writing UTF-8 encoded text. If the file already exists, its contents will be overwritten.

public void CreateFile() {
        //创建或者覆盖文件
        using(StreamWriter fs = File.CreateText(path)) {
            fs.WriteLine("xxxxxxxx");
        }
    }

 

 

Exists(String)     
Determines whether the specified file exists.

public void HaveFile() {
        bool have = File.Exists(path);
        Console.WriteLine($"拥有当前文件:{have}");
    }

Returns true because the file has already been created

Open(String, FileMode)     
Opens a FileStream on the specified path with unshared read/write access.

Open(String, FileMode, FileAccess)     
Opens a FileStream on the specified path with the specified mode and unshared access rights.

public void OpenFile() {
        byte[] array = new byte[] { 1, 1, 1, 1, 1, 1, 1 };
        using(FileStream fs = File.Open(path, FileMode.Open,FileAccess.Read)) {
            fs.Write(array, 0, array.Length);
        }
    }

I write data to the file after opening the file as read-only

after modification

public void OpenFile() {
        byte[] array = new byte[] { 1, 1, 1, 1, 1, 1, 1 };
        using(FileStream fs = File.Open(path, FileMode.Open, FileAccess.ReadWrite)) {
            fs.Write(array, 0, array.Length);
        }
    }

 

You can see that it covers the xxxxxxxx in my previous text, but the length is not enough to completely cover

Open(String, FileMode, FileAccess, FileShare)     
opens a FileStream on the specified path, with the specified mode with read, write, or read/write access, and the specified share options.

Open(String, FileStreamOptions)     
Initializes a new instance of the FileStream class with the specified path, creation mode, read/write and share permissions, access rights other FileStreams can have to the same file, buffer size, additional file options, and allocation size.

OpenRead(String)     
opens an existing file for reading.

Equivalent to File.Open(path, FileMode.Open, FileAccess.Read)

 OpenText(String)     
Opens an existing UTF-8 encoded text file for reading.

Equivalent to:

        FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read);
        StreamReader sr = new StreamReader(fs, Encoding.UTF8);

OpenWrite(String)     
opens an existing file or creates a new file for writing.

Equivalent to File.Open(path, FileMode.Open, FileAccess.Write)

ReadAllBytes(String)     
opens a binary file, reads the contents of the file into a byte array, and closes the file.

public void ReadFile() {
        byte[] array =  File.ReadAllBytes(path);
        for(int i = 0; i < array.Length; i++)
            Console.WriteLine($"打印读取内容:{array[i]}");
    }

ReadAllLines(String)     
opens a text file, reads all lines from the file, and then closes the file.


ReadAllLines(String, Encoding)     
opens a file, reads all lines of the file using the specified encoding, and then closes the file.


ReadAllText(String)     
opens a text file, reads all the text in the file, and then closes the file.


ReadAllText(String, Encoding)     
opens a file, reads all text in the file using the specified encoding, and then closes the file.


ReadLines(String)     
reads the lines of the file.


ReadLines(String, Encoding)     
reads the lines of the file with the specified encoding.

public void ReadFile() {
        foreach(var i in File.ReadLines(path, Encoding.UTF8))
            Console.WriteLine($"打印读取内容:{i}");
    }

 

WriteAllBytes(String, Byte[])     
creates a new file, writes the specified byte array into it, and then closes the file. If the destination file already exists, it is overwritten.

public void WriteFile() {
        byte[] all = new byte[] { 231, 139, 151 };
        File.WriteAllBytes(path, all);
    }

We modify the content of 1.txt to :

then run

 

 After running, it is found that the text content is completely covered (the ones that were longer than before are gone)

WriteAllLines(String, IEnumerable<String>)     
creates a new file, writes a collection of strings to it, and closes the file.


WriteAllLines(String, IEnumerable<String>, Encoding)     
creates a new file using the specified encoding, writes a collection of strings to it, and closes the file.


WriteAllLines(String, String[])     
creates a new file, writes the specified byte array into it, and then closes the file.


WriteAllLines(String, String[], Encoding)     
creates a new file, writes the specified array of strings into it using the specified encoding, and then closes the file.


WriteAllText(String, String)     
creates a new file, writes the specified string to it, and closes the file. If the destination file already exists, it is overwritten.


WriteAllText(String, String, Encoding)     
creates a new file, writes the specified string to it using the specified encoding, and then closes the file. If the destination file already exists, it is overwritten.


Copy(String, String)     
copies an existing file to a new file. Overwriting a file with the same name is not allowed.


Copy(String, String, Boolean)     
copies an existing file to a new file. Allows overwriting files with the same name.

    public void CopyFile() {
        File.Copy(path, @"G:\111\11\1.txt",true);
    }

 
change to false

public void CopyFile() {
        File.Copy(path, @"G:\111\11\1.txt", false);
    }

Move(String, String)     
moves the specified file to a new location, providing the option to specify a new filename.

    public void MoveFile() {
        File.Move(path, @"G:\111\11");
    }

 

 It will report an error when the file exists

Replace(String, String, String)     
replaces the contents of the specified file with the contents of another file, which deletes the original file and creates a backup of the replaced file.

Replace(String, String, String, Boolean)     
replaces the contents of the specified file with the contents of other files. This process will delete the original file and create a backup of the replaced file. Merge errors can also be ignored.

public void ReplaceFile() {
        File.Replace(path, @"G:\111\11\1\2.text", @"G:\111\11\1\3.text");
    }

 When replacing, the file does not exist and an error will be reported

AppendAllLines(String, IEnumerable<String>)     
Appends lines to a file and then closes the file. If the specified file does not exist, this method creates a file, writes the specified line to it, and closes the file.

AppendAllLines(String, IEnumerable<String>, Encoding)     
Appends lines to a file using the specified encoding and then closes the file. If the specified file does not exist, this method creates a file, writes the specified line to it, and closes the file.
Creates a StreamWriter that appends UTF-8 encoded text to an existing file or a new file if the specified file does not exist.

    public void AppFile() {
        List<string> allLine = new List<string>();
        for(int i = 0; i < 5; i++)
            allLine.Add($"xxxxxxx:{i}");
        File.AppendAllLines(path, allLine, Encoding.UTF8);
    }

Only append but not overwrite from the last line or append, if the last line has a newline character, add from the last line to the next line, otherwise the first line is appended to the last line

AppendAllText(String, String)     
opens a file, appends the specified string to it, and then closes the file. If the file does not exist, this method creates a file, writes the specified string to the file, and closes the file.

AppendAllText(String, String, Encoding)     
Appends the specified string to the file using the specified encoding, creating the file if it does not already exist.

    public void AppFile() {
        string contents = "xxxxxxx";
        File.AppendAllText(path, contents, Encoding.UTF8);
    }

 

Encrypt(String)     
encrypts a file so that only the account that encrypted the file can decrypt it.

    public void EncryptFile() {
        File.Encrypt(path);
    }

 

Decrypt(String)     
uses the Encrypt(String) method to decrypt files encrypted by the current account.

public void DecryptFile() {
        File.Decrypt(path);
    }

 

Delete(String)     
delete the specified file

    public void DelectFile() {
        File.Delete(path);
    }

 

file was deleted

2.FileInfo 

Constructor

FileInfo(String)     
Initializes a new instance of the FileInfo class as a wrapper for the file path.

fileInfo = new FileInfo("G:/111/1.text");

Attributes

Directory     
gets an instance of the parent directory.

DirectoryName     
gets a string representing the full path of the directory.

Exists     
gets a value indicating whether the file exists.

IsReadOnly     
Gets or sets a value that determines whether the current file is read-only.

Length     
gets the size of the current file in bytes.

Name     
gets the file name.

public void CreateFileInfo() {
        //没有初始化直接嗲用Exists会报错
        fileInfo = new FileInfo("G:/111/1.text");
        if(fileInfo.Exists) {
            fileInfo.IsReadOnly = false;
            Console.WriteLine($"当前文件是否是只读文件:{fileInfo.IsReadOnly}");
            Console.WriteLine($"当前文件长度为:{fileInfo.Length}");
            Console.WriteLine($"当前文件的名字是:{fileInfo.Name}");
            Console.WriteLine($"打印当前文件的路径:{fileInfo.DirectoryName}");
        }
    }

Print:

 Note: When the file is not initialized, an error will be reported when using fileInfo.Exists


method

AppendText()     
creates a StreamWriter that appends text to the file represented by this instance of FileInfo.

CopyTo(String)     
copies an existing file to a new file, does not allow overwriting of existing files.


CopyTo(String, Boolean)     
Copies an existing file to a new file, allowing existing files to be overwritten.

Create()     
creates a file.  

public void CreateFile() {
        fileInfo = new FileInfo(@"G:\111\11\1\1.txt");
        fileInfo.Create();
    }

If the current file does not exist, fileInfo = new FileInfo cannot create a file. It needs be used in conjunction with file.Create().
If there is already a current file, the new file created will overwrite the original file


CreateText()     
creates a StreamWriter that writes to a new text file.

public void CreateFileText() {
        fileInfo = new FileInfo(@"G:\111\11\1\2.txt");
        using(StreamWriter sw = fileInfo.CreateText()) {
            sw.WriteLine("11111");
        }
    }

Create a file and write the specified content


Decrypt()     
uses the Encrypt() method to decrypt files encrypted by the current account. Similar to File.Decrypt and no longer explained

Delete()     
permanently deletes a file. Similar to File.Delete and no longer explained

Encrypt()     
encrypts a file so that only the account that encrypted the file can decrypt it. Similar to File.Enctypt and no longer explained

MoveTo(String)     
moves the specified file to a new location, providing the option to specify a new file name. Similar to File.Move and no longer explained

Open(FileMode)     
opens the file in the specified mode.


Open(FileMode, FileAccess)     
opens a file in the specified mode with read, write, or read/write access.


Open(FileMode, FileAccess, FileShare)     
opens a file in the specified mode with read, write, or read/write access and the specified sharing options.


OpenRead()     
creates a read-only FileStream.


OpenText()     
creates a StreamReader that uses the UTF8 encoding read from an existing text file.


OpenWrite()     
creates a write-only FileStream.

Similar to File.Open and no longer explained

Replace(String, String)     
replaces the contents of the specified file with the file described by the current FileInfo object. This process will delete the original file and create a backup of the replaced file


Replace(String, String, Boolean)     
replaces the content of the specified file with the file described by the current FileInfo object. This process will delete the original file and create a backup of the replaced file. Also specifies whether to ignore merge errors.

Similar to File.Replace no longer explained

Guess you like

Origin blog.csdn.net/SmillCool/article/details/127446144