我制作了包含listview的exe,所以当我打开一个二进制文件时,它会在列中显示文本指针,在另一列中显示文本字符串。
我设法显示指针,使用“for循环”,但我不知道如何使用循环来显示文本字符串,所以我想要使用的是循环指针,以显示它指向的文本,并在每个文本后停止在00 00.
和here是二进制文件结构的示例。
二进制文件的前4个字节是指针/字符串数量,接下来的4个字节*前4个字节是指针,其余是文本字符串,每个字符串由00 00分隔并且都是Unicode。< / p>
那么有人可以帮我解决如何在字符串列中显示每个指针的字符串吗?
编辑:这是打开二进制文件的按钮的代码:
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;
}
答案 0 :(得分: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]);
}