2012-09-19 20 views
1

我已經使這個exe包含一個列表視圖,所以當我打開一個二進制文件時,它顯示在一列中的文本指針和在另一列中的文本字符串。使用ListView來讀取二進制文件

我設法使用「for循環」顯示指針,但我不知道如何使用循環顯示文本字符串,所以我想要使用的是循環指針,以顯示它指向的文本,並在每個文本後停在00 00。

here是二進制文件結構上的示例。

二進制文件的前4個字節是指針/字符串的數量,接下來的4個字節*前4個字節是指針,其餘是文本字符串,每個字符串被00 00隔開並且都是Unicode。

那麼誰能幫助我如何顯示字符串中的每個指針在字符串列?

編輯:這裏是按鈕打開的二進制文件TEH代碼:

 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; 
    } 
+2

花時間和精力後(相關部分)你的代碼。 –

+1

分而治之 –

+0

增加的代碼,如果你需要其他的東西,請評論。 – Omarrrio

回答

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]); 
} 
+0

** fs **未被聲明,並且'offsetset.Add(br.ReadInt32()); '不會添加任何東西到列表視圖中的指針列,所以我刪除了'br.BaseStream.Position = i * 4 + 4;'它按照你說的那樣工作謝謝你,但仍然沒有得到第二個代碼相當好:s – Omarrrio

+0

您可以用'br.BaseStream.Length'替換'fs'。 (我相應地更新了答案。) – afrischke

+0

仍然無法工作:我將它們添加到按鈕單擊事件中,不應該嗎? 它不顯示字符串,謝謝你的時間:) – Omarrrio