【问题标题】:Read INI file from Windows\System32 folder [duplicate]从 Windows\System32 文件夹中读取 INI 文件 [重复]
【发布时间】:2019-04-22 09:03:58
【问题描述】:

为什么我们无法从 Windows\System32 文件夹中读取 .ini 文件?

使用这个例子:

ReadIniFile := TIniFile.Create(Format('%s\System32\%s', [GetEnvironmentVariable('WINDIR'), 'File.ini']));
Result  := ReadIniFile.ReadString('HWID', 'A', '');
ReadIniFile .Free;

返回一个空字符串,现在如果删除“System32”并尝试从 Windows 文件夹读取正常。

【问题讨论】:

  • 你一定想知道为什么你的目录中有 ini 文件

标签: delphi ini


【解决方案1】:

如果您将应用程序编译为 32 位,但在 64 位版本的 Windows 上运行,那么您的代码实际上是在尝试从 C:\Windows\SysWOW64\ 文件夹而不是 C:\Windows\System32\ 文件夹中读取 INI 文件。有关详细信息,请参阅File System Redirector。在WOW64下运行时可以使用sysnative别名访问真正的System32文件夹:

function GetWindowsFolder: string
var
  Folder: array[0..MAX_PATH-1] of Char;
  Len: UINT;
begin
  Len := GetWindowsDirectory(Folder, MAX_PATH);
  if (Len > 0) and (Len < MAX_PATH) then
    Result := IncludeTrailingPathDelimiter(Folder)
  else;
    Result := '';
end;

function GetSystemFolder: string;
var
  Folder: array[0..MAX_PATH-1] of Char;
  Len: UINT;
begin
  Len := GetSystemDirectory(Folder, MAX_PATH);
  if (Len > 0) and (Len < MAX_PATH) then
    Result := IncludeTrailingPathDelimiter(Folder)
  else
    Result := '';
end;

function GetRealSystem32Folder: string
var
  IsWow64: BOOL;
begin
  if IsWow64Process(GetCurrentProcess(), @IsWow64) and IsWow64 then
  begin
    Result := GetWindowsFolder;
    if Result <> '' then
      Result := Result + 'sysnative' + PathDelim;
  end else
    Result := GetSystemFolder;
end;

...

var
  ReadIniFile: TIniFile;
begin
  ReadIniFile := TIniFile.Create(GetRealSystem32Folder + 'File.ini');
  ...
end;

请注意,sysnative 别名仅适用于 WOW64,因此如果您不想根据是否使用 WOW64 动态格式化文件路径,则可以简单地暂时禁用重定向器:

var
  ReadIniFile: TIniFile;
  SysFolder: array[0..MAX_PATH-1] of Char;
  Len: UINT;
  Value: Pointer;
begin
  Result := '';
  if not Wow64DisableWow64FsRedirection(@Value) then Exit;
  try
    Len := GetSystemDirectory(SysFolder, MAX_PATH);
    if (Len > 0) and (Len < MAX_PATH) then
    begin
      ReadIniFile := TIniFile.Create(IncludeTrailingPathDelimiter(SysFolder) + 'File.ini');
      ...
    end;
  finally
    Wow64RevertWow64FsRedirection(Value);
  end;
end;

【讨论】:

  • 是的,位禁用重定向非常可疑,几乎可以肯定不应该这样做。
  • @DavidHeffernan 也许,尽管在这种情况下,禁用重定向器是安全的,因为禁用的块很小且隔离,并且正在使用的 2 个 Wow64 API 函数仅影响调用线程,而不是全局。当然,使用sysnative 是首选,但禁用重定向器仍然是一个选项,所以我提到两者。
【解决方案2】:

如果您将程序编译为 32 位,它会尝试从 SysWOW64 目录中读取 ini 文件。如果您将程序编译为 64 位,则应该没问题。您可以通过 Wow64DisableWow64FsRedirection 禁用重定向,更多信息: Could not find system file when it actually exists

【讨论】:

  • 这看起来像是禁用重定向的建议。这是个坏主意。
  • 我在问这个问题,因为我需要写一个文件并将其隐藏起来,因为更多的应用程序会读/写它。 (这不是病毒)。对此有何建议?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-29
  • 1970-01-01
  • 1970-01-01
  • 2014-02-20
  • 2013-07-13
  • 1970-01-01
相关资源
最近更新 更多