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

How to read binary files until EOF in C#

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

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