Search code examples
c#binaryreaderbinarywriter

Read and write from/to the same line with BinaryReader/BinaryWriter


I want to read a binary file line by line (I'm writing of course continously, but I know that after 457 bytes new data start and I know exactly the byte structure and where which information is written to) and change a special entry of the line. I get an System.IO.IOException when I try to access the same file with both BinaryReader and BinaryWriter. I use locking to prevent that the file is accessed from somewhere else.

My code is:

using (FileStream fs2 = new FileStream(testfile, FileMode.Open, FileAccess.Read))
{
    using (BinaryReader r = new BinaryReader(fs2))
    {
        using (BinaryWriter bw = new BinaryWriter(new FileStream(testfile, FileMode.Open, FileAccess.Write), utf8))
        {
            for (int i = 0; i < 11000; i+=457)
            {
                int myint = r.ReadInt64();
                bw.Seek(i, SeekOrigin.Current);
                bw.Write(myint*2);
            }
        }
    }
}

How can I do this?


Solution

  • It is working for me using the following code:

    if (File.Exists(testfile))
    {
          FileInfo fi = new FileInfo(testfile);
    
          using (FileStream fs2 = new FileStream(testfile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
          {
              using (BinaryReader r = new BinaryReader(fs2))
              {
                  r.BaseStream.Seek(0, SeekOrigin.Begin);                       
                  using (BinaryWriter bw = new BinaryWriter(new FileStream(testfile, FileMode.Open, FileAccess.Write, FileShare.ReadWrite)))                        
                  {
                      for (int i = 0; i <= (fi.Length-177); i += 177)//181
                      {
                      }
                  }
              }
          }
    }