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);
            } 
        }

  

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

上一篇:数据库设计


下一篇:Posgresql数据库死锁导致数据无法删除