📜  C#中FileStream的基础

📅  最后修改于: 2021-05-29 21:17:03             🧑  作者: Mango

FileStream是用于在C#中读取和写入文件的类。它是System.IO命名空间的一部分。要使用FileStream操作文件,您需要创建FileStream类的对象。该对象具有四个参数;文件名,FileMode,FileAccess和FileShare。

声明FileStream对象的语法为

Parameter Description Fields
Name of the File Name of the file you want to work with along with its extension or the complete path of the file. Eg: FileName.txt, @”C:\Users\Username\Documents\FileName.txt”
FileMode It specifies which mode the file has to be opened in. Open – To open an existing file
Create – To create a new file if the same file name already exists it will be overwritten
OpenOrCreate – To open a file if it exists else create new if it doesn’t
Create – To specifically create a new file
Append – To open an existing file and append more information at the end of the file. If the file doesn’t exist a new file will be created
Truncate – To open a existing file and truncate its size to Zero bytes
FileAccess It specifies the access to the file. – Read – To read data from a file
– Write – To write data to a file
– ReadWrite – To read and write data to a file
FileShare It specifies the access given to other FileStream objects to this particular file – None – To decline the sharing of the file. Any access request will fail until the file is closed.
– Read – To allow subsequent reading of the file.
– Write – To allow subsequent writing to the file.
– ReadWrite – To allow subsequent reading and writing of the file.
– Delete – To allow subsequent deleting of the file.
– Inheritable – To allow the file handle inheritable by child processes.

示例:在下面给出的代码中,我们编写并读取一些文本到文本文件中。要写入文本,请首先在“创建”模式和“写”访问权限下创建FileStream类的对象。将要编写的文本存储在var类型的变量中,这是用于声明隐式类型的关键字。

接下来,创建一个字节数组并将文本编码为UTF8,这是一种编码标准,能够对Unicode中的所有1,112,064个有效字符代码点进行编码。然后使用Write()方法写入文本文件。 Write()方法的参数是要写入的字节数组,文本文件的偏移量和文本的长度。最后,使用Close()关闭FileStream对象。

要读取文本文件,我们在“打开”模式和“读取”访问权限下创建一个FileStream对象。声明一个字节数组以从文本文件读取,并声明一个整数以保持字节数。使用Read()方法从文本文件中读取。 Read()方法的参数是字节数组,从开始读取位置开始的文本文件的偏移量以及必须读取的文本的长度。最后使用GetString()将读取的文本从字节数组写入控制台。

// C# program to write and read from 
// a text file using FileStream class
using System;
using System.IO;
using System.Text;
   
namespace FileStreamWriteRead {
   
class GFG {
   
    static void Main(string[] args)
    {
        // Create a FileStream Object
        // to write to a text file
        // The parameters are complete 
        // path of the text file in the 
        // system, in Create mode, the
        // access to this process is 
        // Write and for other 
        // processes is None
        FileStream fWrite = new FileStream(@"M:\Documents\Textfile.txt",
                     FileMode.Create, FileAccess.Write, FileShare.None);
   
        // Store the text in the variable text
        var text = "This is some text written to the textfile "+
                       "named Textfile using FileStream class.";
   
        // Store the text in a byte array with
        // UTF8 encoding (8-bit Unicode 
        // Transformation Format)
        byte[] writeArr = Encoding.UTF8.GetBytes(text);
   
        // Using the Write method write
        // the encoded byte array to
        // the textfile
        fWrite.Write(writeArr, 0, text.Length);
   
        // Closee the FileStream object
        fWrite.Close();
   
        // Create a FileStream Object
        // to read from a text file
        // The parameters are complete
        // path of the text file in 
        // the system, in Open mode,
        // the access to this process is
        // Read and for other processes
        // is Read as well
        FileStream fRead = new FileStream(@"M:\Documents\Textfile.txt", 
                       FileMode.Open, FileAccess.Read, FileShare.Read);
   
        // Create a byte array 
        // to read from the 
        // text file
        byte[] readArr = new byte[text.Length];
        int count;
   
        // Using the Read method 
        // read until end of file
        while ((count = fRead.Read(readArr, 0, readArr.Length)) > 0) {
            Console.WriteLine(Encoding.UTF8.GetString(readArr, 0, count));
        }
   
        // Close the FileStream Object
        fRead.Close();
        Console.ReadKey();
    }
}
}

输出:

Filetstream在C#中读写