C# file read and write operations [detailed]

A file is a data collection with a specific name and directory path stored on a disk. When we use a program to read or write a file, the program will read the file into the memory in the form of a data stream (stream for short). We can think of a stream as a sequence of bytes passed through a communication path. The stream is mainly divided into an input stream and an output stream. The input stream is mainly used to read data from the file (read operation), and the output stream is mainly used to write to the file. input data (write operation).

I/O classes in C#

The System.IO namespace contains various classes for file operations, such as file creation, deletion, reading, writing, and so on. As shown in the table below:

I/O type describe
BinaryReader read raw data from a binary stream
BinaryWriter write raw data in binary format
BufferedStream Temporary storage of byte streams
Directory Copy, move, rename, create and delete directories
DirectoryInfo Used to perform operations on directories
DriveInfo Get drive information
File operate on the file
FileInfo for performing operations on files
FileStream For reading and writing anywhere in the file
MemoryStream For random access to streams of data stored in memory
Path Perform operations on path information
StreamReader Used to read characters from a byte stream
StreamWriter Used to write characters to a stream
StringReader Used to read data from a string buffer
StringWriter Used to write data to the string buffer

FileStream class

FileStream class in the System.IO namespace, use it to read, write and close files. The syntax for creating a FileStream class object is as follows:

FileStream <object_name> = new FileStream(<file_name>, <FileMode Enumerator>, <FileAccess Enumerator>, <FileShare Enumerator>);

The parameters are described as follows:
object_name : the name of the created object;

file_name : the path of the file (including the file name);

FileMode : enumeration type, used to set the opening mode of the file, the optional values ​​are as follows:

Append : Open an existing file and place the cursor at the end of the file. Create the file if it does not exist;

Create : Create a new file, if the file already exists, delete the old file, and then create a new file;

CreateNew : Create a new file, if the file already exists, throw an exception;

Open : Open an existing file, if the file does not exist, an exception is thrown;

OpenOrCreate : Open an existing file, if the file does not exist, create a new file and open it;

Truncate : Open an existing file, then clear the file (delete the original content), and throw an exception if the file does not exist.

FileAccess : Enumerated type, used to set file access, optional values ​​are Read, ReadWrite and Write;

FileShare : enumerated type, used to set file permissions, the optional values ​​are as follows:

Inheritable : Allow child processes to inherit file handles, Win32 does not directly support this feature;

None : refuse to share the current file until the file is closed, and any request to open the file (by this process or another process) will fail;

Read : Allows subsequent opening of the file for reading. If this flag is not specified, any request to open the file for reading will fail before the file is closed. It should be noted that even if this flag is specified, additional permissions are still required. be able to access the file;

ReadWrite : Allows subsequent opening of the file for reading or writing. If this flag is not specified, any request to open the file for reading or writing will fail until the file is closed. Note that even if this flag is specified , additional permissions are still required to be able to access the file;

Write : Allows subsequent opening of the file for writing. If this flag is not specified, any request to open the file for writing will fail until the file is closed. It should be noted that even if this flag is specified, additional permissions may still be required to be able to access the file;

Delete : Allows subsequent deletion of the file.

For example, we create a FileStream object F to read a file named sample.txt, the sample code is as follows:
FileStream F = new FileStream(“sample.txt”, FileMode.Open, FileAccess.Read, FileShare.Read) ;

Common methods in the FileStream class are as follows:

method describe
Close() Closes the current stream and frees all resources associated with it (such as sockets and file handles)
CopyTo(Stream) read bytes from the current stream and write them to another stream
Dispose() releases all resources used by the Stream
Equals(Object) Determine whether the specified object is equal to the current object
Finalize() Ensures that the garbage collector releases resources and performs other cleanup operations when the FileStream is reclaimed
Flush() Clears the buffer for this stream, causing all buffered data to be written to the file
GetHashCode() default hash function
GetType() Get the Type of the current instance
Lock(Int64, Int64) Prevent other processes from reading or writing to the FileStream
Read(Byte[], Int32, Int32) reads a chunk of bytes from the stream and writes that data into the given buffer
ReadByte() Read a byte from the file and advance the read position by one byte
ToString() Returns a string representing the current object
Unlock(Int64, Int64) Allow other processes to access all or part of a file that was previously locked
Write(Byte[], Int32, Int32) Write chunks of bytes to a file stream
WriteByte(Byte) writes a byte to the current position in the file stream

[Example] Use the FileStream class to read the specified file:

using System;
using System.IO;
namespace c.biancheng.net
{
    
    
    class Demo
    {
    
    
        static void Main(string[] args) 
        {
    
    
            FileStream file = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
            for(int i = 0; i < 20; i++){
    
    
                file.WriteByte((byte)i);
            }
            file.Position = 0;
            for(int i = 0; i < 20; i++){
    
    
                Console.Write(file.ReadByte() + " ");
            }
            file.Close();
            Console.ReadKey();
        }
    }
}

operation result:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

Reading and writing of text files in C#

The StreamReader and StreamWriter classes under the System.IO namespace can be used for data reading and writing of text files. These classes inherit from the abstract base class Stream, which provides functions for reading and writing file streams.

1) StreamReader

The StreamReader class inherits from the abstract base class TextReader and is used to read a series of characters from a file. The following table lists some commonly used methods in the StreamReader class:

method describe
public override void Close() Closes the StreamReader object and underlying stream, and frees any system resources associated with it
public override int Peek() returns the next available character, but does not use it
public override int Read() Read the next character from the input stream and advance the character position by one character

If you want to consult the complete list of methods, you can visit the official API

[Example] Use StreamReader to read the content of the specified file, the content of the file is as follows:

Salary Code
Hello
C# Tutorial

The sample code is as follows:

using System;
using System.IO;
namespace c.biancheng.net
{
    
    
    class Demo
    {
    
    
        static void Main(string[] args) 
        {
    
    
            try{
    
    
                // 创建 StreamReader 类的对象
                StreamReader file = new StreamReader("test.txt");
                string line;
                // 从文件中读取内容
                while((line = file.ReadLine()) != null){
    
    
                    Console.WriteLine(line);
                }
            }catch(Exception e){
    
    
                // 展示出错信息
                Console.WriteLine("无法读取文件");
                Console.WriteLine(e.Message);
            }
            Console.ReadKey();
        }
    }
}

Run the above code to output the contents of the file.

2) StreamWriter

The StreamWriter class also inherits from the abstract class TextWriter and is used to write a series of characters to a file. The following table lists some commonly used methods in the StreamWriter class:

method describe
public override void Close() Closes the current StreamWriter object and the underlying stream
public override void Flush() Clear all current buffers so that all buffered data is written to the underlying stream
public virtual void Write(bool value) 将布尔值的文本表示形式写入文本流
public override void Write(char value) 将一个字符写入流
public virtual void Write(decimal value) 将一个小数值的文本表示形式写入文本流
public virtual void Write(double value) 将一个 8 字节浮点值的文本表示形式写入文本流
public virtual void Write(int value) 将一个 4 字节有符号整数的文本表示形式写入文本流
public override void Write(string value) 将一个字符串写入文本流
public virtual void WriteLine() 将行结束符写入文本流

完整的方法列表请查阅官方API

【示例】向文件中写入指定内容。

using System;
using System.IO;
namespace c.biancheng.net
{
    
    
    class Demo
    {
    
    
        static void Main(string[] args) 
        {
    
    
            // 要写入文件中的数据
            string[] str = new string[]{
    
    
                "薪薪代码",
                "你好",
                "C# 教程"
            };
            // 创建 StreamWriter 类的对象
            StreamWriter file = new StreamWriter("demo.txt");
            // 将数组中的数据写入文件
            foreach(string s in str){
    
    
                file.WriteLine(s);
            }
            file.Close();
            // 读取文件中的内容
            string line = "";
            StreamReader readfile = new StreamReader("demo.txt");
            while((line = readfile.ReadLine()) != null){
    
    
                Console.WriteLine(line);
            }
            readfile.Close();
            Console.ReadKey();
        }
    }
}

运行结果如下:

薪薪代码
你好
C# 教程

二进制文件读写

C# 中的 BinaryReader 和 BinaryWriter 类可以用于二进制文件的读写。

1) BinaryReader 类

BinaryReader 类用于从文件读取二进制数据,类中的常用方法如下所示:

方法 描述
public override void Close() 关闭 BinaryReader 对象和基础流
public virtual int Read() 从基础流中读取字符,并根据所使用的编码和从流中读取的特定字符,将流的当前位置前移
public virtual bool ReadBoolean() 从当前流中读取一个布尔值,并将流的当前位置前移一个字节
public virtual byte ReadByte() 从当前流中读取下一个字节,并将流的当前位置前移一个字节
public virtual byte[] ReadBytes(int count) 从当前流中读取指定数目的字节到一个字节数组中,并将流的当前位置前移指定数目的字节
public virtual char ReadChar() 从当前流中读取下一个字节,并把流的当前位置按照所使用的编码和从流中读取的指定的字符往前移
public virtual char[] ReadChars(int count) 从当前流中读取指定数目的字符,并以字符数组的形式返回数据,并把流的当前位置按照所使用的编码和从流中读取的指定的字符往前移
public virtual double ReadDouble() 从当前流中读取一个 8 字节浮点值,并把流的当前位置前移八个字节
public virtual int ReadInt32() 从当前流中读取一个 4 字节有符号整数,并把流的当前位置前移四个字节
public virtual string ReadString() 从当前流中读取一个字符串,字符串以长度作为前缀,同时编码为一个七位的整数

完整的方法列表请查阅 官方API

2) BinaryWriter 类

BinaryWriter 类用于向文件写入二进制数据,类中的常用方法如下表所示:

方法 描述
public override void Close() 关闭 BinaryWriter 对象和基础流
public virtual void Flush() 清理当前编写器的所有缓冲区,使得所有缓冲数据写入基础设备
public virtual long Seek(int offset,SeekOrigin origin) 设置当前流中的位置
public virtual void Write(bool value) 将一个字节的布尔值写入到当前流中,0 表示 false,1 表示 true
public virtual void Write(byte value) 将一个无符号字节写入到当前流中,并把流的位置前移一个字节
public virtual void Write(byte[] buffer) 将一个字节数组写入到基础流中
public virtual void Write(char ch) 将一个 Unicode 字符写入到当前流中,并把流的当前位置按照所使用的编码和要写入到流中的指定字符往前移
public virtual void Write(char[] chars) 将一个字符数组写入到当前流中,并把流的当前位置按照所使用的编码和要写入到流中的指定字符往前移
public virtual void Write(double value) 将一个 8 字节浮点值写入到当前流中,并把流位置前移八个字节
public virtual void Write(int value) 将一个 4 字节有符号整数写入到当前流中,并把流位置前移四个字节
public virtual void Write(string value) 将一个有长度前缀的字符串按 BinaryWriter 的当前编码写如到流中,并把流的当前位置按照所使用的编码和要写入到流中的指定字符往前移

完整的方法列表请查阅官方API

【示例】下面通过示例演示二进制文件的读取和写入:

using System;
using System.IO;
namespace c.biancheng.net
{
    
    
    class Demo
    {
    
    
        static void Main(string[] args) 
        {
    
    
            BinaryWriter bw;
            BinaryReader br;
            int i = 520;
            double d = 3.14159;
            bool b = true;
            string s = "薪薪代码";
            // 创建文件
            try{
    
    
                bw = new BinaryWriter(new FileStream("mydata", FileMode.Create));
            }catch (IOException e){
    
    
                Console.WriteLine(e.Message + "\n 文件创建失败!");
                return;
            }
            // 写入文件
            try{
    
    
                bw.Write(i);
                bw.Write(d);
                bw.Write(b);
                bw.Write(s);
            }catch (IOException e){
    
    
                Console.WriteLine(e.Message + "\n 文件写入失败!");
            }
            bw.Close();
            // 读取文件
            try{
    
    
                br = new BinaryReader(new FileStream("mydata", FileMode.Open));
            }catch (IOException e){
    
    
                Console.WriteLine(e.Message + "\n 文件打开失败!");
                return;
            }
            try{
    
    
                i = br.ReadInt32();
                Console.WriteLine("Integer data: {0}", i);
                d = br.ReadDouble();
                Console.WriteLine("Double data: {0}", d);
                b = br.ReadBoolean();
                Console.WriteLine("Boolean data: {0}", b);
                s = br.ReadString();
                Console.WriteLine("String data: {0}", s);
            }catch (IOException e){
    
    
                Console.WriteLine(e.Message + "\n 文件读取失败!.");
            }
            br.Close();
            Console.ReadKey();
        }
    }
}

运行结果:

Integer data: 520
Double data: 3.14159
Boolean data: True
String data:薪薪代码

Guess you like

Origin blog.csdn.net/m0_65636467/article/details/129116475