gpt4 book ai didi

c# - 如何在 C# 中读取二进制文件直到 EOF

转载 作者:太空宇宙 更新时间:2023-11-03 12:08:44 24 4
gpt4 key购买 nike

我有一个函数可以将一些数据写入二进制文件

private void writeToBinFile (List<MyClass> myObjList, string filePath)
{
FileStream fs = new FileStream(filePath, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);

foreach (MyClass myObj in myObjList)
{
bw.Write(JsonConvert.SerializeObject(myObj));
}
bw.Close();
fs.Close();

}

我看起来像

FileStream fs = new FileStream(filePath, FileMode.Create);
BinaryReader bw = new BinaryReader(fs);

while (!filePath.EOF)
{
List<MyClass> myObjList = br.Read(myFile);
}

有人可以帮忙吗?提前致谢

最佳答案

JSON 可以无格式保存(无新行),因此您可以在文件的每一行保存 1 条记录。因此,我建议的解决方案是忽略二进制文件,而是使用常规的 StreamWriter:

private void WriteToFile(List<MyClass> myObjList, string filePath)
{
using (StreamWriter sw = File.CreateText(filePath))
{
foreach (MyClass myObj in myObjList)
{
sw.Write(JsonConvert.SerializeObject(myObj, Newtonsoft.Json.Formatting.None));
}
}
}

private List<MyClass> ReadFromFile(string filePath)
{
List<MyClass> myObjList = new List<MyClass>();
using (StreamReader sr = File.OpenText(filePath))
{
string line = null;
while ((line = sr.ReadLine()) != null)
{
myObjList.Add(JsonConvert.DeserializeObject<MyClass>(line));
}
}
return myObjList;
}

如果你真的想用binary writer来保存JSON,你可以改成这样:

private void WriteToBinFile(List<MyClass> myObjList, string filePath)
{
using (FileStream fs = new FileStream(filePath, FileMode.Create))
using (BinaryWriter bw = new BinaryWriter(fs))
{
foreach (MyClass myObj in myObjList)
{
bw.Write(JsonConvert.SerializeObject(myObj));
}
}
}

private List<MyClass> ReadFromBinFile(string filePath)
{
List<MyClass> myObjList = new List<MyClass>();
using (FileStream fs = new FileStream(filePath, FileAccess.Read))
using (BinaryReader br = new BinaryReader(fs))
{
while (fs.Length != fs.Position) // This will throw an exception for non-seekable streams (stream.CanSeek == false), but filestreams are seekable so it's OK here
{
myObjList.Add(JsonConvert.DeserializeObject<MyClass>(br.ReadString()));
}
}
return myObjList;
}

注意事项:

  • 我添加了 using围绕流实例化,以便在释放内存时正确关闭文件
  • 要检查流是否在末尾,您必须将 LengthPosition 进行比较。

关于c# - 如何在 C# 中读取二进制文件直到 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53511297/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com