C# 之 FileStream类介绍

FileStream类

FileStream(文件流) 这个类主要用于二进制文件中读写,也可以使用它读写任何文件。

StreamReader(流读取器)和StreamWriter(流写入器)专门用于读写文本文件

使用FileStream读写二进制文件:
FileStream实例用于读写文件中的数据,要构造FileStream实例,需要提供下面的4中信息:

  1. 要访问的文件
    一般提供一个文件的完整路径名
  2. 表示如何打开文件的模式
    新建文件或打开一个现有文件,如果打开一个现有的文件,写入操作是覆盖文件原来的内容,还是追加到文件的末尾?
  3. 表示访问文件的方式
    只读、只写、还是读写
  4. 共享访问
    表示是否独占访问文件,如果允许其他流同时访问文件,则这些流是只读 只写 还是读写文件

构造函数的参数:

  • FileMode( 打开模式) Append,Create,CreateNew,Open,OpenOrCreate和Truncate
  • FileAccess(读取还是写入) Read,ReadWrite和Write
  • FileShare(文件共享设置) Delete,Inheritable,None,Read,ReadWrite和Write

PS:
如果文件不存在Append OpenTruncate会抛出异常, 如果文件存在 CreateNew会抛出异常; CreateOpenOrCreateCreate会删除现有的文件,新建一个空的文件,OpenOrCreate会判断当前是否有文件,没有的话才会创建;

注意事项:
当我们使用完了一个流之后,一定要调用fs.Close();方法去关闭流,关闭流会释放与它相关联的资源,允许其他应用程序为同一个文件设置流。这个操作也会刷新缓冲区。


示例代码

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

namespace CSharpDemo
{
    
    
    class Programma
    {
    
    
        static void Main(string[] args)
        {
    
    
            string path = @"E:\MyTest.txt";
            if (File.Exists(path)) // 校验文件是否存在
            {
    
    
                File.Delete(path);
            }
           
            // 创建并写入文件
            using (FileStream fs_write = File.Create(path))
            {
    
    
                byte[] info = new UTF8Encoding(true).GetBytes("123");
                fs_write.Write(info, 0, info.Length);
                byte[] info1 = new UTF8Encoding(true).GetBytes("456789");
                fs_write.Write(info1, 0, info1.Length);
            }

            // 读取文件
            using (FileStream fs_read = File.OpenRead(path))
            {
    
    
                byte[] byteArr = new byte[1024];
                UTF8Encoding coding = new UTF8Encoding(true);
                while (fs_read.Read(byteArr, 0, byteArr.Length) > 0)
                {
    
    
                    Console.WriteLine(coding.GetString(byteArr));
                }
            }
            Console.ReadKey();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/Czhenya/article/details/123992864