2013-04-17 78 views
0

我希望能得到關於這個問題的一些幫助,所以你可以在圖片波紋管看,我似乎無法達到讀取整個字爲0x00: enter image description hereC#二進制閱讀殘缺串

什麼我試圖OT做的,是剛剛讀取文件中的字符串正確,這裏是我用來打開文件的代碼:

 private void menuItem2_Click(object sender, EventArgs e) 
    { 
     listView1.Items.Clear(); 
     textBox1.Text = ""; 
     menuItem12.Text = "file type is: "; 
     OpenFileDialog ofd = new OpenFileDialog(); 
     ofd.Title = "Open File"; 
     ofd.Filter = "All Files (*.*)|*.*"; 
     if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
     { 
      path = ofd.FileName; 
      BinaryReader br = new BinaryReader(File.OpenRead(path), Encoding.GetEncoding("SHIFT-JIS")); 
      foreach (char mychar in br.ReadChars(4)) menuItem12.Text += mychar; 
      if (menuItem12.Text != "file type is: TXTD") 
      { 
       MessageBox.Show("This is not a TXTD file...", "Sorry", MessageBoxButtons.OK, MessageBoxIcon.Error); 
       return; 
      } 
      else 
      { 
        MessageBox.Show("File opened Succesfully!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information); 
        br.BaseStream.Position = 0x8; 
        int Pntrnum = br.ReadInt16(); 
        menuItem11.Visible = true; 
        menuItem11.Text = Pntrnum.ToString(); 
        List<int> offsets = new List<int>(); 
        br.BaseStream.Position = 0x10; 
        for (int i = 0; i < Pntrnum; i++) 
        { 
         offsets.Add(br.ReadInt32()); 
        } 
        Dictionary<int, string> values = new Dictionary<int, string>(); 
        for (int i = 0; i < offsets.Count; i++) 
        { 
         int currentOffset = offsets[i]; 

         int nextOffset = (i + 1) < offsets.Count ? offsets[i + 1] : (int)br.BaseStream.Length; 

         int stringLength = (nextOffset - currentOffset - 1)/2; 

         br.BaseStream.Position = currentOffset; 

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

        foreach (int offset in offsets) 
        { 
         listView1.Items.Add(offset.ToString("X")).SubItems.Add(values[offset]); 
        } 

        br.Close(); 
        br = null; 
      } 
     } 
     ofd.Dispose(); 
     ofd = null; 
    } 
+1

在'stringLength =(nextOffset - currentOffset - 1)/ 2'中,爲什麼要除以2? (我認爲「SHIFT-JIS」編碼在ASCII範圍內有單字節字符)。 –

+0

謝謝先生,沒有看到它,請張貼它作爲解決方案,所以我可以選擇它:)再次感謝你 – Omarrrio

回答

2

的「SHIFT-JIS」編碼使用單字節的ASCII字符範圍。

我可以看到你的文字是ASCII,但此行的代碼:

stringLength = (nextOffset - currentOffset - 1)/2; 

被假定字符佔用兩個字節。

1

爲了二進制數據轉換爲正確的字符串,你應該知道Encodings。所以你可以在System.Text.Encoding找到一些有用的編碼。然後你就可以字節數組轉換爲字符串,像這樣:

byte[] byteArray = // your byte array 
System.Text.Encoding encoding = Encoding.UTF8; //use proper encoding 
string value = encoding.GetString(byteArray); 

你也可以看到MSDN