本文介绍了使用BinaryWriter和BinaryReader操作搜索c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些像roll,name和mark这样的数据。我把这些写到文件中。喜欢
Hi,
I have some data like roll, name and mark. I have written these to a file. Like
FileStream fs = new FileStream("data.dat",FileMode.OpenOrCreate);
BinaryWriter br = new BinaryWriter(fs);
br.Write(Convert.ToInt32(textBox1.Text)); //Textbox1 for int roll
br.Write(textBox2.Text); // Textbox2 for string name
br.Write(Convert.ToInt32(textBox3.Text)); //Textbox3 for int mark
fs.Flush();
br.Flush();
fs.Close();
br.Close();
我们每次都可以使用BinaryWriter在新行中写一个像roll,name和merk这样的新记录。我们每次使用BinaryReader都可以读取新行。
现在我必须使用BinaryReader类从该文件中搜索基于roll的任何记录。如何在文本框中输入卷并从文件中搜索记录。
谢谢。
Can we write a new record like roll, name and merk in new line every time using BinaryWriter. Can we read new line every time using BinaryReader.
Now I have to search any record based on roll from that file using BinaryReader class . How can i enter a roll in textbox and search the record from file.
Thank you.
推荐答案
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) {
// It is important to read all the values here in the order
// they were written, not just the search item.
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);
}
}
}
}
希望这有帮助,
Fredrik
Hope this helps,
Fredrik
这篇关于使用BinaryWriter和BinaryReader操作搜索c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!