To search a file written using
BinaryReader
you can sequentially read the elements in the same order they were written whilst checking some condition.
The below example show appending two items to a file and then trying to find one of them again using the
string
value as a condition:
using System;
using System.IO;
namespace Stuff {
class Program {
private static void Append(int a, string b, int c) {
using (var fs = new FileStream(@"C:\Temp\data.dat", FileMode.Append)) {
using (var br = new BinaryWriter(fs)) {
br.Write(a);
br.Write(b);
br.Write(c);
}
}
}
private static bool TryFindString(string s, out int a, out int c) {
a = 0;
c = 0;
using (var fs = new FileStream(@"C:\Temp\data.dat", FileMode.Open)) {
using (var br = new BinaryReader(fs)) {
while (fs.CanRead) {
a = br.ReadInt32();
var b = br.ReadString();
c = br.ReadInt32();
if (s == b)
return true;
}
}
}
return false;
}
static void Main(string[] args) {
Append(1, "A", 100);
Append(2, "B", 200);
int a, c;
if (TryFindString("B", out a, out c)) {
Console.WriteLine("Found string {0}, a={1} and b={2}", "B", a, c);
}
}
}
}
Hope this helps,
Fredrik