c# filestream 类常用的函数 FileMode 常用的属性

c# filestream 类常用的函数

FileStream类是C#中用于读写文件的类,它继承自Stream类,提供了一些额外的文件操作方法。下面是FileStream类常用的一些方法:

FileStream(string path, FileMode mode): 创建一个指定路径和打开方式的FileStream对象。其中,path参数是文件路径,mode参数是打开方式,如FileMode.Create表示创建新文件并打开,FileMode.Open表示打开现有文件,FileMode.Append表示打开现有文件并将指针定位到文件末尾等等。

string filePath = @"D:\test.txt";
FileStream fs = new FileStream(filePath, FileMode.Create);

FileStream.Seek(long offset, SeekOrigin origin): 将文件指针定位到指定位置。其中,offset参数是相对于origin参数指定的位置的偏移量。origin参数是一个枚举类型,表示指针移动的参考位置,如SeekOrigin.Begin表示从文件开头开始,SeekOrigin.Current表示从当前位置开始,SeekOrigin.End表示从文件结尾开始。

// 将文件指针定位到文件末尾
fs.Seek(0, SeekOrigin.End);

FileStream.Read(byte[] buffer, int offset, int count): 从文件中读取指定长度的字节数据,并将其存储到指定的字节数组中。其中,buffer参数是用于存储数据的字节数组,offset参数是buffer数组的起始位置,count`参数是要读取的字节数。

byte[] data = new byte[1024];
int bytesRead = fs.Read(data, 0, data.Length);

FileStream.Write(byte[] buffer, int offset, int count): 向文件中写入指定长度的字节数据。其中,buffer参数是要写入的字节数组,offset参数是buffer数组的起始位置,count参数是要写入的字节数。

byte[] data = Encoding.UTF8.GetBytes("Hello, world!");
fs.Write(data, 0, data.Length);

FileStream.Flush(): 将缓冲区中的数据写入文件。在使用FileStream类进行写操作时,写入的数据通常会先存储在缓冲区中,调用Flush方法可以将缓冲区中的数据强制写入文件。

fs.Write(data, 0, data.Length);
fs.Flush();
FileMode 枚举类型

FileMode 枚举类型定义了打开文件时所使用的不同模式。下面列举了 FileMode 常用的属性:

Append: 如果文件存在,将数据追加到文件的末尾;否则,创建一个新文件。

示例:

using (FileStream fs = new FileStream("example.txt", FileMode.Append))
{
    byte[] bytes = Encoding.UTF8.GetBytes("Hello, World!");
    fs.Write(bytes, 0, bytes.Length);
}

Create`: 如果文件不存在,则创建一个新文件;如果文件存在,则覆盖原文件。

示例:

using (FileStream fs = new FileStream("example.txt", FileMode.Create))
{
    byte[] bytes = Encoding.UTF8.GetBytes("Hello, World!");
    fs.Write(bytes, 0, bytes.Length);
}

Open: 打开现有文件。

示例:

using (FileStream fs = new FileStream("example.txt", FileMode.Open))
{
    // 读取数据
    byte[] buffer = new byte[1024];
    int bytesRead = fs.Read(buffer, 0, buffer.Length);
    string text = Encoding.UTF8.GetString(buffer, 0, bytesRead);
    Console.WriteLine(text);
}

OpenOrCreate: 如果文件存在,则打开该文件;否则,创建一个新文件。

示例:

using (FileStream fs = new FileStream("example.txt", FileMode.OpenOrCreate))
{
    byte[] bytes = Encoding.UTF8.GetBytes("Hello, World!");
    fs.Write(bytes, 0, bytes.Length);
}

Truncate: 如果文件存在,则将其截断为零长度;否则,创建一个新文件。

示例:

using (FileStream fs = new FileStream("example.txt", FileMode.Truncate))
{
    // 文件内容被截断为空
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值