One article can explain the flow in C# clearly

What is flow in computer programming

In computer programming, a stream is an object of a class, and the input and output operations of many files are provided in the form of member functions of the class.

C# includes the following standard IO (input/output) classes, which can be read/written from different sources (such as files, memory, network, isolated storage, etc.).

Stream: System.IO.Stream is an abstract class that provides a standard method for transferring bytes (read, write, etc.) to the source. Transfer bytes just like a wrapper class. Classes that need to read/write bytes from a specific source must implement the Stream class.

The following classes inherit the Stream class to provide the ability to read/write bytes from a specific source:

  • FileStream: Read bytes from a physical file or write bytes to a physical file, whether it is .txt, .exe, .jpg or any other file. FileStream is derived from the Stream class.
  • MemoryStream: MemoryStream reads or writes bytes stored in memory.
  • BufferedStream: BufferedStream reads or writes bytes from other Streams to improve the performance of certain I/O operations.
  • NetworkStream: NetworkStream reads or writes bytes from a network socket.
  • PipeStream: PipeStream reads or writes bytes from different processes.
  • CryptoStream: CryptoStream is used to link the data stream to the cryptographic conversion.

C# StreamReader class: read files

In the C# language, the StreamReader class is used to read strings from the stream. It inherits from the TextReader class. There are many construction methods for the treamReader class. Here are some commonly used construction methods, as shown in the figure below.
Insert picture description here
Use the construction method in the table to create an instance of the StreamReader class, and call the class members provided by the instance to read files. The common properties and methods in the StreamReader class are shown in the following figure.
Insert picture description here
example:

using System;
using System.IO;

namespace MySpace
{
    
    

    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            //定义文件路径
            string path = @"E:\test\test.txt";

            //创建StreamReader对象
            StreamReader streamReader = new StreamReader(path);

            //获取流中的下一个字节的整数,如果没有获取到字符,则返回-1
            //获取获取全部字节
            while(streamReader.Peek() != -1)
            {
    
    
                //从当前流中读取一行字符并将数据作为字符串返回
                string str = streamReader.ReadLine();
                Console.WriteLine(str);
            }
            //关闭流
            streamReader.Close();
            Console.ReadKey();
        }
    }
}

operation result:
Insert picture description here

C# StreamWriter class: write files

The StreamReader class corresponds to the StreamWriter class. The StreamWriter class is mainly used to write data to the stream.
There are also many construction methods for the StreamWriter class. Here are only some commonly used construction methods, as shown in the figure below.
Insert picture description here
After creating an instance of the StreamWriter class, you can call its class members to complete the operation of writing information to the file. The properties and methods commonly used in the StreamWriter class are shown in the following figure.
Insert picture description here
The Write, WriteAsync, and WriteLineAsync methods also have many overloads for different types of writes, which are not listed here.

example:

using System;
using System.IO;

namespace MySpace
{
    
    
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            string path = @"E:\test\test.txt";
            //创建一个StreamWriter的对象
            StreamWriter streamWriter = new StreamWriter(path);

            //向文件中写入一个行
            streamWriter.WriteLine("QQ:");

            streamWriter.WriteLine("845264718");
            //刷新缓冲
            streamWriter.Flush();
            //关闭流
            streamWriter.Close();

       

        }
    }
}

operation result:

Insert picture description here

C# FileStream class: file read and write

In the C# language, the file read and write stream is represented by the FileStream class. The FileStream class is mainly used to read and write files. It can not only read and write ordinary text files, but also read files in different formats such as image files and sound files.

When creating an instance of the FileStream class, multiple enumerated values ​​are involved, including FileAccess, FileMode, FileShare, FileOptions, etc.

The FileAccess enumeration type is mainly used to set the access method of the file. The specific enumeration values ​​are as follows.

  • Read: Open the file as read-only.
  • Write: Open the file in writing mode.
  • ReadWrite: Open the file in read-write mode.

The FileMode enumeration type is mainly used to set the method of file opening or creation. The specific enumeration values ​​are as follows.

  • CreateNew: Create a new file. If the file already exists, an exception will be thrown. Create: Create a file. If the file does not exist, delete the original file and recreate the file.

  • Open: Open an existing file. If the file does not exist, an exception will be thrown. OpenOrCreate: Open an existing file, if the file does not exist, create the file.

  • Truncate: Open an existing file and clear the contents of the file, keeping the creation date of the file. If the file does not exist, an exception will be thrown.

  • Append: Open the file, used to append content to the file, if the file does not exist, create a new file.

The FileShare enumeration type is mainly used to set the access control when multiple objects access the same file at the same time. The specific enumeration values ​​are as follows.

  • None: Decline to share the current file.
  • Read: Allow subsequent opening of the file to read information.
  • ReadWrite: Allow subsequent opening of the file to read and write information.
  • Write: Allow subsequent opening of the file to write information.
  • Delete: Allow subsequent deletion of files.
  • Inheritable: The file handle can be inherited by the child process.

The FileOptions enumeration type is used to set the advanced options of the file, including whether the file is encrypted, whether to delete after access, etc. The specific enumeration values ​​are as follows.

  • WriteThrough: Indicates that the system should write directly to disk through any intermediate cache.
  • None: Indicates that no other options should be used when generating System.IO.FileStream objects.
  • Encrypted: Indicates that the file is encrypted and can only be decrypted by the same user account used for encryption.
  • DeleteOnClose: Indicates that a file is automatically deleted when it is no longer used.
  • SequentialScan: Indicate to access files in order from beginning to end. RandomAccess: Indicate random access to files.
  • Asynchronous: Indicates that the file can be used for asynchronous reading and writing.

There are many construction methods for the FileStream class. Here are some commonly used construction methods, as shown in the figure below.
Insert picture description here
After creating an instance of the FileStream class, you can call the members of the class to complete the operation of reading and writing data. The commonly used properties and methods in the FileStream class are shown in the following figure.
Insert picture description here
Example 1:


using System;
using System.IO;
using System.Text;//  byte[] bytes = Encoding.UTF8.GetBytes(msg);所用到的名字空间

namespace MySpcae
{
    
    
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            //定义文件路径
            string path = @"E:\test\QQ.txt";
            ///创建FileStream类的对象
            ///第一参数path是文件路径
            ///第二个参数FileMode.OpenOrCreate 打开已存在的文件,不存在就创建
            ///第三个参数FileAccess.ReadWrite  以读写打开文件
            ///第四个参数FileShare.ReadWrite  允许随后打开文件读写信息
            FileStream fileStream = new FileStream(path, FileMode.OpenOrCreate,
                FileAccess.ReadWrite, FileShare.ReadWrite);
            string msg = "845264718";
            //如果是中文,那么string长度不够用,将数据从字符串类型装换成字节类型
            byte[] bytes = Encoding.UTF8.GetBytes(msg);
            //从流中读取字节快并将该数据写入给定的缓冲区
            //bytes是字节块
            //0是位置
            //bytes.Length是字节块的大小
            fileStream.Write(bytes, 0, bytes.Length);
            //刷新缓冲区
            fileStream.Flush();
            //关闭流
            fileStream.Close();
        }
    }
}

Operation result:
Insert picture description here
Example 2 :

using System;
using System.IO;
using System.Text;

namespace MySpace
{
    
    
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            //指定文件路径
            string path = @"E:\test\QQ.txt";
            //判断是否含有指定文件
            if(File.Exists(path))
            {
    
    

                FileStream fileStream = new FileStream(path,
                    FileMode.Open, FileAccess.Read);
                //定义存放文件信息的字节数组
                byte[] bytes = new byte[fileStream.Length];
                fileStream.Read(bytes, 0, bytes.Length);
                //将得到的字节类型数组重写编码为字符型数组
                char[] c = Encoding.UTF8.GetChars(bytes);
                Console.WriteLine("My QQ:");
                Console.WriteLine(c);
                //关闭流
                fileStream.Close();
            }
            else
            {
    
    
                Console.WriteLine("您查看的文件不存在!");
            }
            Console.ReadKey();
        }
    }

}

operation result:
Insert picture description here

C# BinaryReader class: read binary files

The BinaryReader class is used when reading data in binary form in C#. There are three construction methods provided in the BinaryReader class, and the specific syntax forms are as follows.

The first form:

BinaryReader(Stream input)   //其中,input 参数是输入流。

The second form:

BinaryReader(Stream input, Encoding encoding)   //其中,input 是指输入流,encoding 是指编码方式。

The third form:

BinaryReader(Stream input, Encoding encoding, bool leaveOpen)  //其中,input 是指输入流,encoding 是指编码方式,leaveOpen 是指在流读取后是否包括流的打开状态。

After completing the creation of the instance of the BinaryReader class, the file can be read in binary form.

The common properties and methods in the BinaryReader class are shown in the figure below.
Insert picture description here
The method provided in the BinaryReader class does not directly read the value of the specified data type in the file, but reads the value written to the file by the BinaryWriter class.

Among the above methods, only the Read method does not require that the value read must be written to the file by the BinaryWriter class.

Example 1:

using System;
using System.IO;

namespace MySpace
{
    
    
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            //只读方式创建文件流
            FileStream fileStream = new FileStream(@"E:\test\test.txt",
                FileMode.Open);
            //创建一个BinaryRead的对象
            BinaryReader binaryReader = new BinaryReader(fileStream);
            //从指定的流中读取字符
            int a = binaryReader.Read();
            //判断文件中是否含有字符,若不含字节,a的值为-1
            while(a != -1)
            {
    
    
                //输出读取到的字符
                Console.Write((char)a);
                a = binaryReader.Read();
            }
            Console.WriteLine();
            Console.ReadKey();
        }
    }
}

Running result:
Insert picture description here
In addition to using the Read method to read one character at a time, you can also use other overloaded methods of the Read method to read characters into a byte array or character array.

Example 2:

using System;
using System.IO;
using System.Text;


namespace MySpace
{
    
    
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            //创建一个文件流对象,设定了打开方式,和只读权限
            FileStream fileStream = new FileStream(@"E:\test\test.txt",
                FileMode.Open, FileAccess.Read);
            //创建一个BinaryReader对象
            BinaryReader binaryReader = new BinaryReader(fileStream);
            //获取文件长度
            long length = fileStream.Length;
            byte[] bytes = new byte[length];
            //读取的文件内容并保存到字节数组中
            binaryReader.Read(bytes, 0, bytes.Length);
            //将字节数组转换为字符串
            String str = Encoding.Default.GetString(bytes);
            Console.WriteLine(str);

            Console.ReadKey();
        }
    }

    
}

operation result:
Insert picture description here

C# BinaryWriter class: write binary data

The BinaryWriter class is used to write content to the stream. The specific grammatical form of its construction method is as follows.

The first form:

BinaryWriter(Stream output)

The second form:

BinaryWriter(Stream output, Encoding encoding)

The third form:

BinaryWriter(Stream output, Encoding encoding, bool leaveOpen)

The properties and methods commonly used in the BinaryWriter class are shown in the following figure.
Insert picture description here
In addition to the above methods, the Write method also provides multiple types of overloaded methods.

example:

using System;
using System.IO;

namespace MySpace
{
    
    

    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            //创建一个文件写入流对象,存在就打开,权限是写
            FileStream fileStream = new FileStream(@"E:\test\test.txt",
                FileMode.Open, FileAccess.Write);
            //创建一个写入二进制流
            BinaryWriter binaryWriter = new BinaryWriter(fileStream);
            //向文件写入
            binaryWriter.Write("一起来学习啊");
            binaryWriter.Write(8456264718);
            //刷新缓冲区,将缓冲区内容写入文件中
            binaryWriter.Flush();
            binaryWriter.Close();
            //关闭二进制流
            fileStream.Close();
            //创建一个文件读取流,存在就打开,权限只读
            fileStream = new FileStream(@"E:\test\test.txt",
                FileMode.Open, FileAccess.Read);
            //创建一个二进制读取流
            BinaryReader binaryReader = new BinaryReader(fileStream);
            //读取数据显示到屏幕
            Console.WriteLine(binaryReader.ReadString());
            Console.WriteLine(binaryReader.ReadInt64());
            //关闭流
            binaryReader.Close();
            fileStream.Close();
        }
            
    }
}

operation result:
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_50188452/article/details/115026555