Good day to all, please help me figure out how to add data to a binary file? There is a code that writes the value to the file:

using (BinaryWriter WriteNr = new BinaryWriter( File.Open( path2, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite ) )) { WriteNr.Write(Line); WriteNr.Close(); } 

But when you add a new record, the old one is erased, ie the file is overwritten, how to make the old records remain and the new ones added? Please help me figure it out.

When reading a file, only the latest data still gets, here's how I read the file:

 using (BinaryReader reader2 = new BinaryReader( File.Open( path2, FileMode.Open, FileAccess.Read, FileShare.ReadWrite ) )) { while (reader.PeekChar() > -1) { Nr++; Line = reader.ReadInt32();} 

I need to read from beginning to end and write down if there are no matches, but I cannot check it because the data is constantly taken, the last ones are written, and not in order.

    1 answer 1

    Change FileMode.OpenOrCreate to FileMode.Append and it will be recorded.

    Record example:

     private static void AppendData(string filename, int intData, string stringData, byte[] lotsOfData) { using (var fileStream = new FileStream(filename, FileMode.Append, FileAccess.Write, FileShare.None)) using (var bw = new BinaryWriter(fileStream)) { bw.Write(intData); bw.Write(stringData); bw.Write(lotsOfData); } } 
    • Thank you very much. But it did not help when reading the file, the last recorded data - Ethernets
    • using (BinaryReader reader2 = new BinaryReader(File.Open(path2, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))) { while (reader.PeekChar() > -1) { Nr++; Line = reader.ReadInt32();} using (BinaryReader reader2 = new BinaryReader(File.Open(path2, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))) { while (reader.PeekChar() > -1) { Nr++; Line = reader.ReadInt32();} This is how to read from the file - Ethernets
    • @Ethernets, add a better question. - iluxa1810
    • @Ethernets, and you have FileMode.Open, and you need Append. - iluxa1810
    • then I get an exception that the combination FileMode.Append and FileAccess.Read are not allowed - Ethernets