【问题标题】:Convert object to byte[]将对象转换为字节[]
【发布时间】:2011-01-13 20:20:42
【问题描述】:

我正在尝试将检索到的注册表值从 object 转换为 byte[]。它存储为REG_BINARY。我尝试使用BinaryFormatterMemoryStream。但是,它添加了我不想要的开销信息。当我通过执行函数Convert.ToBase64String(..) 将字节数组转换为字符串时,我观察到了这一点。我正在执行这些功能,因为我正在测试注册表中加密密钥的存储和检索。

【问题讨论】:

    标签: c# object bytearray memorystream binaryformatter


    【解决方案1】:

    如果它是一个 REG_BINARY,那么当你检索它时它应该已经 是一个字节数组...你不能将它转换为 byte[] 吗?

    或者,如果您尚未验证它在代码中是 REG_BINARY,您可能希望使用:

    byte[] binaryData = value as byte[];
    if (binaryData == null)
    {
        // Handle case where value wasn't found, or wasn't binary data
    }
    else
    {
        // Use binaryData here
    }
    

    【讨论】:

    • 好的,是的,这就是答案。我有一段时间没有使用 C#,所以很明显我生疏了。感谢您发布明显的答案:)
    【解决方案2】:

    试试这个。如果它已经是一个 REG_BINARY,你需要做的就是转换它:

    static byte[] GetFoo()
    {
    
      var obj = Microsoft.Win32.Registry.GetValue("HKEY_LOCAL_MACHINE\\Software", "foo", null);
      //TODO: Write a better exception for when it isn't found
      if (obj == null) throw new Exception(); 
    
      var bytearray = obj as byte[];
      //TODO: Write a better exception for when its found but not a REG_BINARY
      if (bytearray == null) throw new Exception(); 
    
      return bytearray;
    }
    

    【讨论】:

      【解决方案3】:

      如果您使用 Convert.ToBase64String 转换它,您应该能够以类似方式将其取出。

      string regValueAsString = (string)regValueAsObj;
      byte[] buf = Convert.FromBase64String(regValueAsString);
      

      【讨论】:

        猜你喜欢
        • 2011-09-19
        • 1970-01-01
        • 1970-01-01
        • 2011-06-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-04-02
        相关资源
        最近更新 更多