繁体   English   中英

在 C# 中使用 BinaryReader 读取 DAT 文件

[英]Reading a DAT file with BinaryReader in C#

我正在尝试使用 BinaryReady 读取 DAT 文件,但出现异常并且不明白为什么。 “无法在流的末尾阅读”是我得到的消息。 我的代码如下所示:

private void button1_Click(object sender, EventArgs e)

    {
        OpenFileDialog OpenFileDialog = new OpenFileDialog();
        OpenFileDialog.Title = "Open File...";
        OpenFileDialog.Filter = "Binary File (*.dat)|*.dat";
        OpenFileDialog.InitialDirectory = @"C:\";
        if (OpenFileDialog.ShowDialog() == DialogResult.OK)
        {
            FileStream fs = new FileStream(OpenFileDialog.FileName, FileMode.Open);
            BinaryReader br = new BinaryReader(fs);

            label1.Text = br.ReadString();
            label2.Text = br.ReadInt32().ToString();

            fs.Close();
            br.Close();
        }

我有一个包含大量信息的特定 DAT 文件,并希望能够将其读出,甚至可能将其放入表格中并绘制数据。 但是我使用 C# 已经有一段时间了。 所以如果有人能帮助我,我将不胜感激

BinaryReader很少是读取外部文件的好选择; 它只有在与使用BinaryWriter编写文件的代码并行使用时才真正有意义,因为它们使用相同的约定。

这里发生的事情是您对ReadString的调用试图使用对您的文件无效的约定 - 具体来说,它将读取一些字节(我想说 4,大端?)作为长度前缀对于字符串,然后尝试读取与字符串一样多的字节。 但是,如果这不是文件内容:那很容易尝试读取乱码,将其解释为一个巨大的数字,然后无法读取那么多字节。

如果您正在处理任意文件(与BinaryWriter无关),那么您确实需要了解很多有关协议/格式的信息。 鉴于文件扩展名不明确,我不会从“.dat”中推断出任何内容——重要的是:数据什么以及它来自哪里? . 只有有了这些信息,才能对阅读做出明智的评论。


从评论中,这里有一些(未经测试的)代码,可以帮助您开始将内容解析为跨度:

public static YourResultType Process(string path)
{
    byte[] oversized = null;
    try
    {
        int len, offset = 0, read;
        // read the file into a leased buffer, for simplicity
        using (var stream = File.OpenRead(path))
        {
            len = checked((int)stream.Length);
            oversized = ArrayPool<byte>.Shared.Rent(len);
            while (offset < len &&
                (read = stream.Read(oversized, offset, len - offset)) > 0)
            {
                offset += read;
            }
        }
        // now process the payload from the buffered data
        return Process(new ReadOnlySpan<byte>(oversized, 0, len));
    }
    finally
    {
        if (oversized is object)
            ArrayPool<byte>.Shared.Return(oversized);
    }
}
private static YourResultType Process(ReadOnlySpan<byte> payload)
    => throw new NotImplementedException(); // your code here

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM