如何使用 Delphi 获取 INI 文件的绝对路径?

How do I get the absolute path of an INI file with Delphi?

如果我使用这个 Delphi 代码

with TIniFile.Create('myapp.ini') do
try
  WriteString('SETTINGS', 'key', 'value');
finally
  Free;
end;

要在默认文件夹中创建 INI 文件,有没有办法检索 Windows 用于创建文件的绝对路径?

在后台,TInifile.WriteString 使用 WritePrivateProfileString 函数。

来自文档(强调我的):

BOOL WINAPI WritePrivateProfileString(   _In_ LPCTSTR lpAppName,  
    _In_ LPCTSTR lpKeyName,   _In_ LPCTSTR lpString,   
    _In_ LPCTSTR lpFileName );

lpAppName [in]

The name of the section to which the string will be copied. If the section does not exist, it is created. The name of the section is case-independent; the string can be any combination of uppercase and lowercase letters.

lpKeyName [in] The name of the key to be associated with a string. If the key does not exist in the specified section, it is created. If this parameter is NULL, the entire section, including all entries within the section, is deleted.

lpString [in] A null-terminated string to be written to the file. If this parameter is NULL, the key pointed to by the lpKeyName parameter is deleted.

lpFileName [in] The name of the initialization file. If the file was created using Unicode characters, the function writes Unicode characters to the file. Otherwise, the function writes ANSI characters.

If the lpFileName parameter does not contain a full path and file name for the file, WritePrivateProfileString searches the Windows directory for the file. If the file does not exist, this function creates the file in the Windows directory.

最后一条评论意味着您的程序必须 运行 作为管理员。逻辑结果是,如果您的程序不是 运行 作为管理员,则默认路径将是 C:\Users\Windows username\AppData\Local\VirtualStore\Windows。 因此,要遵守现代 windows 规则,最好为 ini 文件提供完整路径...