• C# FileStream设置了FileAccess.ReadWrite, FileShare.ReadWrite依然报“流不可读”或者“流不可写”


    今天遇见一个诡异的事情,我用FileStream操作一个文件的时候,明明设置了FileAccess.ReadWrite, FileShare.ReadWrite了,但是依然报错,说是“流不可写”

    后来仔细一研究才发现,原来是我用的不对,我是在FileStream里面先用了BinaryReader,然后又用了BinaryWriter,貌似不能这么用,一个FileStream只能用做一次操作

    static void AAA() {
                using (FileStream fs = new FileStream("E:\test.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) {
                    using (BinaryReader br = new BinaryReader(fs)) {
                        Console.WriteLine(br.ReadByte());
                        br.Dispose();
                    } 
                    using (BinaryWriter bw = new BinaryWriter(fs)) {  //一个FileStream只能进行一次Binary操作,第二次就会报错
    
                    }
                }
            }
    

      不知道为什么using包裹着BinaryReader也不行,我还想着重用一个流呢,估计是没彻底释放之类的,想要不报错,就需要给BinaryWriter再申请一次FileStream

    static void AAA() {
                using (FileStream fs = new FileStream("E:\test.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) {
                    using (BinaryReader br = new BinaryReader(fs)) {
                        Console.WriteLine(br.ReadByte());
                        br.Dispose();
                    }
    
                }
                using (FileStream fs = new FileStream("E:\test.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) {
                    using (BinaryWriter bw = new BinaryWriter(fs)) {  //每个Binary操作都申请一次FileStream就不会报错了
    
                    }
                }
            }
    

      或者干脆直接用FileStream自己操作算了

    static void AAA() {
                using (FileStream fs = new FileStream("E:\test.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) {
                    Console.WriteLine(fs.ReadByte());
                    fs.Seek(0,SeekOrigin.Begin);
                    fs.WriteByte(0xFF);
                } 
            }
    

      

  • 相关阅读:
    如何制作a2sd+
    WinForm/Silverlight多线程编程中如何更新UI控件的值
    c#如何操作cookie
    Windows Mobile CookieContainer
    Microsoft.Practices.EnterpriseLibrary.Data 数据库操作
    获取手机卡imei和imsi信息
    winform 分页控件
    asp.net 导出数据到Excle
    asp.net异步调用
    shell脚本中常用命令
  • 原文地址:https://www.cnblogs.com/luludongxu/p/14821476.html
Copyright © 2020-2023  润新知