如何解决将硬盘驱动器串行字符串写入二进制文件
| 我有一个简单的函数,可以从C:\\驱动器获取硬盘驱动器序列号,并将其放入字符串中:ManagementObject disk = new ManagementObject(\"win32_logicaldisk.deviceid=\\\"C:\\\"\");
disk.Get();
string hdStr = Convert.ToString(disk[\"VolumeSerialNumber\"]);
然后,我尝试将上面的字符串转换为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());
}
谁能帮助我了解如何添加这些内容?
解决方法
尝试这个:
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;
}
, 尝试使用System.Text.Encoding.ASCII.GetBytes(hdStr)获得表示ASCII字符串的字节。
, 文件中字节顺序对您有多重要?
也许您可以使用类似:
byte[] b = BitConverter.GetBytes(Convert.ToUInt32(hdStr,16));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。