1

我制作了这个包含列表视图的 exe,因此当我打开二进制文件时,它会在一列中显示文本指针,在另一列中显示文本字符串。

我设法使用“for循环”显示指针,但我不知道如何使用循环显示文本字符串,所以我想使用的是循环指针,显示它指向的文本到,并在每个文本之后停止在 00 00。

是二进制文件结构的示例。

二进制文件的前 4 个字节是指针/字符串量,接下来的 4 个字节 * 第 1 个 4 个字节是指针,其余的是文本字符串,每个字符串由 00 00 分隔,都是 Unicode。

那么任何人都可以帮助我如何在字符串列中显示每个指针的字符串吗?

编辑:这是打开二进制文件的按钮的代码:

        private void menuItem8_Click(object sender, EventArgs e)
    {
        textBox1.Text = "";
        OpenFileDialog ofd = new OpenFileDialog();
        ofd.Title = "Open File";
        ofd.Filter = "Data Files (*.dat)|*.dat|All Files (*.*)|*.*";
        if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            MessageBox.Show("File opened Succesfully!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
            path = ofd.FileName;
            BinaryReader br = new BinaryReader(File.OpenRead(path));               
            int num_pointers = br.ReadInt32();
            textBox1.Text = num_pointers.ToString();
            for (int i = 0; i < num_pointers; i++)
            {
                br.BaseStream.Position = i * 4 + 4;
                listView1.Items.Add(br.ReadUInt32().ToString("X"));
            }
            br.Close();
            br = null;
        }
        ofd.Dispose();
        ofd = null;
    }
4

1 回答 1

0

首先,在实例化 BinaryReader 时提供编码,如下所示:

BinaryReader br = new BinaryReader(File.OpenRead(path), Encoding.Unicode);

接下来,您要保留读取偏移量的列表。(您仍然可以稍后将它们添加到 ListView):

List<int> offsets = new List<int>();
for (int i = 0; i < num_pointers; i++)
{
    // Note: There is no need to set the position in the stream as
    // the Read method will advance the stream to the next position
    // automatically.
    // br.BaseStream.Position = i * 4 + 4;
    offsets.Add(br.ReadInt32());
}

最后,您浏览偏移列表并从文件中读取字符串。您可能希望将它们放入一些数据结构中,以便稍后您可以使用数据填充视图:

Dictionary<int,string> values = new Dictionary<int,string>();
for (int i = 0; i < offsets.Count; i++)
{
    int currentOffset = offsets[i];

    // If it is the last offset we just read until the end of the stream
    int nextOffset = (i + 1) < offsets.Count ? offsets[i + 1] : (int)br.BaseStream.Length;

    // Note: Under the supplied encoding, a character will take 2 bytes.
    // Therefore we will need to divide the delta (in bytes) by 2.
    int stringLength = (nextOffset - currentOffset - 1) / 2;

    br.BaseStream.Position = currentOffset;

    var chars = br.ReadChars(stringLength);
    values.Add(currentOffset, new String(chars));
}

// Now populate the view with the data...
foreach(int offset in offsets)
{
    listView1.Items.Add(offset.ToString("X")).SubItems.Add(values[offset]);
}
于 2012-09-19T11:14:47.400 回答