2011-05-27 49 views
3

我有一個簡單的功能,抓住從C硬盤序列號:\驅動器,並把它轉換成字符串:寫作硬盤序列串爲二進制文件

​​

然後我試圖轉換將上面的字符串轉換成ASCII碼,然後將其寫入二進制文件,我遇到的問題是,在轉換此字符串並使用streamwriter保存文件並在十六進制編輯器中打開該文件時,我看到更多的字節我原本想這樣寫例如「16342D1F4A61BC」

將出現爲:08 16 34 2d 1f 4a 61 c2 bc

它添加在那裏不知何故08和C2 ......

更完整版如下:

string constructor2 = "16342D1F4A61BC"; 
string StrValue = ""; 

while (constructor2.Length > 0) 
{ 
    StrValue += System.Convert.ToChar(System.Convert.ToUInt32(constructor2.Substring(0, 2), 16)).ToString(); 
    // Remove from the hex object the converted value 
    constructor2 = constructor2.Substring(2, constructor2.Length - 2); 
} 

FileStream writeStream; 
try 
{ 
    writeStream = new FileStream(Path.GetDirectoryName(Application.ExecutablePath) + "\\license.mgr", FileMode.Create); 
    BinaryWriter writeBinay = new BinaryWriter(writeStream); 
    writeBinay.Write(StrValue); 
    writeBinay.Close(); 
} 
catch (Exception ex) 
{ 
    MessageBox.Show(ex.ToString()); 
} 

誰能幫助我瞭解這些在獲取添加?

+0

你不能直接寫輸出? – tofutim 2011-05-27 17:34:17

+4

while循環的目的是什麼?有一個方便的Encoding.ASCII.GetBytes(字符串),它會從任何字符串返回必要的字節。 – Joe 2011-05-27 17:34:22

+0

我想你是說當你以十六進制查看你的輸出文件時,你想看到硬盤ID的十六進制表示。 – tofutim 2011-05-27 17:48:56

回答

0

嘗試使用System.Text.Encoding.ASCII。GetBytes(hdStr)以ASCII格式獲取表示字符串的字節。

+0

@tofutim,我不能直接寫它如果我使用System.Text.Encoding.ASCII如下所示,我需要將十六進制字符串的ascii表示形式寫入二進制文件:writeBinay.Write(System.Text.Encoding。 ASCII.GetBytes(hdStr));當我在十六進制編輯器中查看寫入文件時,它看起來像這樣:31 36 33 34 32 44 31 46 34 41 36 31 42 43(16342D1F4A61BC) – 2011-05-27 17:40:39

+0

啊 - 你想寫出字符串的十六進制而不是ASCII字節。好。 – 2011-05-27 18:27:57

1

試試這個:

string constructor2 = "16342D1F4A61BC"; 
File.WriteAllBytes("test.bin", ToBytesFromHexa(constructor2)); 

用下面的輔助函數:

public static byte[] ToBytesFromHexa(string text) 
{ 
    if (text == null) 
     throw new ArgumentNullException("text"); 

     List<byte> bytes = new List<byte>(); 
    bool low = false; 
    byte prev = 0; 

    for (int i = 0; i < text.Length ; i++) 
    { 
     byte b = GetHexaByte(text[i]); 
     if (b == 0xFF) 
      continue; 

     if (low) 
     { 
      bytes.Add((byte)(prev * 16 + b)); 
     } 
     else 
     { 
      prev = b; 
     } 
     low = !low; 
    } 
    return bytes.ToArray(); 
} 

public static byte GetHexaByte(char c) 
{ 
    if ((c >= '0') && (c <= '9')) 
     return (byte)(c - '0'); 

    if ((c >= 'A') && (c <= 'F')) 
     return (byte)(c - 'A' + 10); 

    if ((c >= 'a') && (c <= 'f')) 
     return (byte)(c - 'a' + 10); 

    return 0xFF; 
} 
+0

西蒙!這正是我想要它做的,非常感謝你! – 2011-05-27 17:51:05

0

如何重要的是字節序到您的文件嗎?

或許你可以使用類似:

byte[] b = BitConverter.GetBytes(Convert.ToUInt32(hdStr, 16));