C# FileStream简单介绍和使用

本文深入讲解了FileStream类的基本功能,包括创建、读写操作、文件共享、缓冲区设置等,并提供了多个示例,如文件复制、读取和写入等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本章讲述:FileStream类的基本功能,以及简单示例;

1、引用命名空间:using System.IO;

2、注意:使用IO操作文件时,要注意流关闭和释放问题!

    强力推荐:将创建文件流对象的过程写在using当中,会自动帮助我们释放资源;

    使用try{} catch(Exception ex){} 进行一次捕获;

3、FileStream 操作字节,可以操作任何类型的文件;下面来简单介绍FileStream类的方法和参数:

    (1)FileStream()    作用:创建FileStream对象,参数:第一个是路径,第二个是文件模式FileMode枚举,第三个数据模式FileAcess

    FileStream(String, FileMode):
    FileStream(String, FileMode, FileAccess)
    FileStream(String, FileMode, FileAccess, FileShare)
    FileStream(String, FileMode, FileAccess, FileShare, Int32)

        初始化FileStream时使用包含文件共享属性(System.IO.FileShare)的构造函数比使用自定义线程锁更为安全和高效

    (2)FileMode(以何种方式打开或者创建文件):CreateNew(创建新文件)、Create(创建并覆盖)、Open(打开)、OpenOrCreate(打开并创建)、Truncate(覆盖文件)、Append(追加);

    (3)FileAcess(文件流对象如何访问该文件):Read(只读) 、Write(写)、ReadWirte(读写);

    (4)FileShare(进程如何共享文件):None(拒绝共享)、Read 、Write、ReadWrite(同时读写)、Delete;

    (5)bufferSize(缓冲区大小设置)

4、Stream.Read(array<Byte[], Int32, Int32):从流中读取一块字节,并将数据写入给定的缓冲区;

5、Stream.Write(array<Byte[], Int32, Int32):使用缓冲区中的数据将字节块写入此流;

6、close():关闭当前流并释放与当前流关联的任何资源(如套接字和文件句柄);

7、dispose():释放流所有使用的资源;

8、CopyTo(Stream):从当前流中读取所有字节并将其写入目标流。 

     CopyTo(Stream, Int32):从当前流中读取所有字节,并使用指定的缓冲区大小将它们写入目标流

9、Seek()(FileStream类维护内部文件指针,该指针指向文件中进行下一次读写操作的位置):将此流的当前位置设置为给定值。(stream.seek(Int64,SeekOrigin)

     第一个参数规定文件指针以字节为单位的移动距离。第二个参数规定开始计算的起始位置;SeekOrigin枚举包含3个值:Begin、Current 和 End;

     例如:aFile.Seek(0, SeekOrigin.End);

10、由于设置了文件共享模式为允许随后写入,所以即使多个线程同时写入文件,也会等待之前的线程写入结束之后再执行,而不会出现错误

using (FileStream logFile = new FileStream(logFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write))

11、简单示例1:简单文件写入

FileStream devStream = new FileStream(devPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite,512);
devStream.Write(data, 0, 128);

if(devStream != null)
    devStream.Close();

12、简单示例2:以追加的方式写入文件

public static class MonitData
{
    public static string devPath = string.Empty;
    private static object objLock = new object();
    public static void WriteInfo(byte[] data)
    {
        lock (objLock)
        {
            if (!string.IsNullOrEmpty(devPath))
            {
                byte[] byteArray = new byte[128];
                Array.Copy(data, 0, byteArray, 0, 128);
                if (byteArray != null && byteArray.Length == 128)
                {
                        using (System.IO.FileStream fs = System.IO.File.OpenWrite(devPath))
                        {
                            fs.Seek(0, SeekOrigin.End);
                            fs.Write(byteArray, 0, byteArray.Length);
                            fs.Close();
                            fs.Dispose();
                        }
                }
            }
        }  
    }
}

13、简单示例:文件流写入

public static void Main(string[] args)
{
    String str = @"E:\下载\软件";
    Stopwatch sw = new Stopwatch();
    sw.Start();
    using (FileStream fsWriter = new FileStream(str + @"\opencv-3.0.exe", FileMode.Create, FileAccess.Write))
    {
        using (FileStream fsReader = new FileStream(str + @"\opencv-2.4.9.exe", FileMode.Open, FileAccess.Read))
        {
            byte[] bytes=new byte[1024*4];//4kB是合适的;
            int readNum;
            while((readNum=fsReader.Read(bytes,0,bytes.Length))!=0)//小于说明读完了
            {
                fsWriter.Write(bytes,0,readNum);
                fsWriter .Flush();//清除缓冲区,把所有数据写入文件中
            }
            fsWriter.Close();
            fsWriter.Dispose();
        }
    }
    sw.Stop();
    Console.WriteLine("总的运行时间为{0}",sw.ElapsedMilliseconds);
    Console.ReadKey();
}

14、简单示例:读取文件

public static string FileStreamReadFile(string filePath)
{
    byte[] data = new byte[100];
    char[] charData = new char[100];
    FileStream file = new FileStream(filePath, FileMode.Open);
    //文件指针指向0位置
    file.Seek(0, SeekOrigin.Begin);//可以设置第一个参数
    //读入两百个字节
    file.Read(data, 0, (int) file.Length);
    //提取字节数组
    Decoder dec = Encoding.UTF8.GetDecoder();
    dec.GetChars(data, 0, data.Length, charData, 0);
    file.Close();    
    file.Dispose();
    return Convert.ToString(charData);
}

### C# 中 `FileStream` `StreamWriter` 的用法及区别 #### 使用 `FileStream` `FileStream` 是用于读取写入文件的基础类。它提供了对文件的字节级访问,允许直接操作二进制数据。 ```csharp using System; using System.IO; class FileStreamExample { public static void Main() { string filePath = "example.bin"; byte[] dataToWrite = { 0x1A, 0x2B, 0x3C }; // 创建并打开文件流以写入模式 using (FileStream fs = new FileStream(filePath, FileMode.Create)) { fs.Write(dataToWrite, 0, dataToWrite.Length); } // 打开文件流以读取模式 using (FileStream fs = new FileStream(filePath, FileMode.Open)) { byte[] buffer = new byte[dataToWrite.Length]; int bytesRead = fs.Read(buffer, 0, buffer.Length); foreach (byte b in buffer) { Console.WriteLine($"Byte: {b:X}"); } } } } ``` 此代码展示了如何创建一个文件并将一些字节写入其中,然后再将其读回[^2]。 #### 使用 `StreamWriter` `StreamWriter` 提供了一种更高级的方式处理基于字符的数据流。通常情况下,当需要编写文本到文件时会使用这个类。它可以自动管理编码转换,并提供方便的方法来写出字符串其他基本类型的值。 ```csharp using System; using System.IO; class StreamWriterExample { public static void Main() { string textFilePath = "example.txt"; // 将文本写入文件 using (StreamWriter sw = new StreamWriter(textFilePath)) { sw.WriteLine("First line"); sw.WriteLine("Second line with number: {0}", 42); } // 从文件中读取文本(这里为了展示效果,实际上应该用 StreamReader) using (StreamReader sr = new StreamReader(textFilePath)) { while (!sr.EndOfStream) { Console.WriteLine(sr.ReadLine()); } } } } ``` 这段程序说明了怎样利用 `StreamWriter` 向文本文件追加多行文字以及简单地遍历这些记录。 #### 主要差异 - **抽象层次**:`FileStream` 处理的是原始字节数组;而 `StreamWriter` 则面向更高层的应用场景——即处理人类可读的文字串。 - **功能特性**:由于 `StreamWriter` 构建于 `FileStream` 上面,因此除了继承后者的能力外还增加了诸如自动换行符调整等功能支持多种平台间的兼容性问题解决方法。 - **性能考量**:对于纯文本的操作来说,`StreamWriter` 更高效也更容易上手;但如果涉及到复杂的二进制格式,则应考虑直接采用底层的 `FileStream` 进行精确控制。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值