C# file read/write fileshare doesn't appear to work

后端 未结 3 844
挽巷
挽巷 2020-12-14 03:08

My question is based off of inheriting a great deal of legacy code that I can\'t do very much about. Basically, I have a device that will produce a block of data. A librar

相关标签:
3条回答
  • 2020-12-14 03:39

    Your consumer must specify FileShare.ReadWrite.

    By trying to open the file as FileShare.Read in the consumer you are saying "I want to open the file and let others read it at the same time" ... since there is already a writer that call fails, you have to allow concurrent writes with the reader.

    0 讨论(0)
  • 2020-12-14 03:58

    I believe Chuck is right, but keep in mind The only reason this works at all is because the filesystem is smart enough to serialize your read/writes; you have no locking on the file resource - that's not a good thing :)

    0 讨论(0)
  • 2020-12-14 03:59

    I haven't had time to test this but I think you may need to call the Flush method of the BinaryWriter

    FileStream theFS = new FileStream(this.ScannerRawFileName, 
      FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
    //note that I need to be able to read this elsewhere...
    BinaryWriter theBinaryWriter = new BinaryWriter(theFS);
    int y, x;
    for (y = 0; y < imheight; y++){
        ushort[] theData= new ushort[imwidth];
        for(x = 0; x < imwidth;x++){
           theData[x] = (ushort)(2*y+4*x);
        }
        byte[] theNewArray = new byte[imwidth * 2];
        Buffer.BlockCopy(theImage, 0, theNewArray, 0, imwidth * 2);
        theBinaryWriter.Write(theNewArray);
        Thread.Sleep(mScanThreadWait); //sleep for 50 milliseconds
        Progress = (float)(y-1 >= 0 ? y-1 : 0) / (float)imheight;
        theBinaryWriter.Flush();
    }
    theFS.Close();
    

    Sorry I haven't had time to test this. I ran into an issue with a file I was creating that was similar to this (although not exact) and a missing "Flush" was the culprit.

    0 讨论(0)
提交回复
热议问题