C# - 在Windows 7 Phone中将byte[]转换为String

3

你好,我正在尝试使用以下代码获取Windows 7手机的设备ID:

 byte[] result = null;
 String id = null;
 object uniqueId;
 if (DeviceExtendedProperties.TryGetValue("DeviceUniqueId", out uniqueId))
     result = (byte[])uniqueId;

问题是我需要将结果转换为字符串。请问有谁能告诉我如何做到这一点? 最好的问候

2个回答

9
string myString = Convert.ToBase64String(result);

这个功能可在Windows Phone 7平台上使用。

http://msdn.microsoft.com/zh-cn/library/dhx0d524(VS.95).aspx

如果您需要再次获取字节数组,只需像这样请求即可。

byte[] byteArray = Convert.FromBase64String(myString);

编辑:Curt提供了将其转换回字节数组的正确方法。


1
为了从Base 64字符串中获取原始字节,你需要使用Convert.FromBase64String(),而不是像上面展示的GetBytes()。 - Curt Nichols

2
System.Text.Encoding.UTF8.GetString(myBytes, 0, myBytes.Length);

我没有检查过,但我认为这种方法在Windows Phone上是可用的。

当我这样做时,调试器中的结果以特殊字符的形式显示。 - Aqueel
这是我使用您发布的代码后得到的结果。Nʝ���Z�����ʻj�l"� - Aqueel
有没有规定"DeviceUniqueId"必须是可读的文本? - herzmeister

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接