Hello;
using c# , I want to build a small database in which its data can be stored in Records (struct) , it seems difficult to do so using streamwriter , and I searched binarywriter to find any member doing like that but I didn't find any thing , any help well appreciated ,, thank you

Dani AI

Generated

Both approaches in this thread are valid; pick the one that fits your access pattern. As pointed out, low-level random-access files (fixed-size binary records + seek) still make sense when you must update records in place with minimal overhead. As found, object serialization is far easier when you only append/read whole objects or want human-readable files.

For a modern, safe serializer use the built-in System.Text.Json. It handles structs and classes, is fast, and avoids the security/compatibility issues of BinaryFormatter (do not use BinaryFormatter in new code) — see the official guidance and API docs: System.Text.Json overview and BinaryFormatter security guidance.

Example (JSON):

using System.Text.Json;

public struct MyRecord { public int Id { get; set; } public string Name { get; set; } }

var r = new MyRecord { Id = 1, Name = "Alice" };
File.WriteAllText("data.json", JsonSerializer.Serialize(r));
var read = JsonSerializer.Deserialize<MyRecord>(File.ReadAllText("data.json"));

If you need true random access and fixed-size records (fast point updates), use FileStream + BinaryWriter/BinaryReader with a fixed byte layout and Seek to the record offset. Keep encoding consistent and compute recordSize precisely so offsets are stable. See FileStream.Seek for details: FileStream.Seek.

Example (binary fixed-size record):

int recordSize = 4 + 20; // int32 + 20-byte name field
using var fs = new FileStream("data.bin", FileMode.OpenOrCreate, FileAccess.ReadWrite);
using var bw = new BinaryWriter(fs, Encoding.UTF8);
fs.Seek(recordIndex * recordSize, SeekOrigin.Begin);
// write int then fixed-length name bytes (pad/truncate to 20)

If you need querying, indexing, or concurrency, consider a small embedded DB like SQLite (sqlite.org). Also remember: structs are value types — use them only for small, immutable data; for richer records prefer classes or C# record types (see Microsoft guidance on choosing between class and struct).

Recommended Answers

All 2 Replies

look up how to work with random-access files i think this would be the best way to store records

Thank you but Random Acces File s is an old fashion now , it has a new techniqe in c# as I found here , you can read this

"Serialization is the process of converting complex objects into stream of bytes for storage. Deserialization is its reverse process."

http://www.codeproject.com/csharp/ObjSerial.asp

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.