如何使用Delphi 2010远程读取二进制注册表数据?

时间:2010-10-12 18:25:12

标签: delphi delphi-2009 delphi-2010

我正在尝试远程读取二进制(REG_BINARY)注册表值,但我得到的只是垃圾回复。任何想法这个代码有什么问题?我正在使用Delphi 2010:

function GetBinaryRegistryData(ARootKey: HKEY; AKey, AValue, sMachine: string; var sResult: string): boolean;
    var
      MyReg: TRegistry;
      RegDataType: TRegDataType;
      DataSize, Len: integer;
      sBinData: string;
      bResult: Boolean;
    begin
      bResult := False;
      MyReg := TRegistry.Create(KEY_QUERY_VALUE);

      try
        MyReg.RootKey := ARootKey;
        if MyReg.RegistryConnect('\\' + sMachine) then
        begin
          if MyReg.KeyExists(AKey) then
          begin
            if MyReg.OpenKeyReadOnly(AKey) then
            begin
              try
                RegDataType := MyReg.GetDataType(AValue);
                if RegDataType = rdBinary then
                begin
                  DataSize := MyReg.GetDataSize(AValue);
                  if DataSize > 0 then
                  begin
                    SetLength(sBinData, DataSize);
                    Len := MyReg.ReadBinaryData(AValue, PChar(sBinData)^, DataSize);
                    if Len <> DataSize then
                      raise Exception.Create(SysErrorMessage(ERROR_CANTREAD))
                    else
                    begin
                      sResult := sBinData;
                      bResult := True;
                    end;
                  end;
                end;
              except
                MyReg.CloseKey;
              end;
              MyReg.CloseKey;
            end;
          end;
        end;
      finally
        MyReg.Free;
      end;

      Result := bResult;
    end;

我称之为:

GetBinaryRegistryData(
   HKEY_LOCAL_MACHINE, 
   '\SOFTWARE\Microsoft\Windows NT\CurrentVersion', 
   'DigitalProductId', '192.168.100.105', 
   sProductId
);

WriteLn(sProductId);

我从控制台上的WriteLn收到的结果是:

ñ ♥ ???????????6Z ????1   ???????☺  ???♦            ??3   ? ??? ?
??

2 个答案:

答案 0 :(得分:5)

您正在使用Delphi 2010,因此您的所有字符都是两个字节宽。设置结果字符串的长度时,您需要分配两次所需的空间量。然后你打电话给ReadBinaryData,它填充一半你的缓冲区。每个字符中有两个字节的数据。分别查看每个字节,您可能会发现您的数据看起来不像垃圾一样。

不要使用字符串来存储任意数据。使用字符串存储文本。要存储任意数据blob,请使用TBytes,这是一个字节数组。

答案 1 :(得分:5)

假设您已远程连接,请尝试使用GetDataAsString功能 从注册表中读取二进制数据。

sResult := MyReg.GetDataAsString(AValue);