Writing a serial line of a hard disk to a binary file

I have a simple function that captures the serial number of a hard drive from C: \ and puts it on a line:

ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"C:\"");
disk.Get();
string hdStr = Convert.ToString(disk["VolumeSerialNumber"]);

Then I try to convert the line above to ASCII and then write it to a binary file, the problem I encountered is converting this line and saving the file using streamwriter and opening the file in hex editor, I see more bytes that I initially wanted to write, for example, "16342D1F4A61BC"

Will be like: 08 16 34 2d 1f 4a 61 c2 bc

He adds 08 and c2 there somehow ...

A more complete version is as follows:

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());
}

Can someone help me understand how they are added?

+3
source share
3 answers

Try the following:

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

System.Text.Encoding.ASCII.GetBytes(hdStr), , ASCII.

0

How important is the information in the file for you?

Perhaps you can use something like:

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

All Articles