此错误通常是由于尝试写入应用程序自己的文件夹而引起的Program Files
,对于 Vista 及更高版本(以及 XP,如果您不以管理员或高级用户身份运行)下的非管理员来说,这是不允许的。
以下是获取 .INI 文件正确文件夹的一些代码:
uses
Windows,
ShlObj; // For SHGetSpecialFolderPath
function GetFolderLocation(Handle: HWnd; Folder: Integer): string;
begin
Result := '';
SetLength(Result, MAX_PATH);
if not SHGetSpecialFolderPath(Handle, PChar(Result), Folder, False) then
RaiseLastOSError;
end;
我在应用程序中使用这些来检索非漫游配置文件文件夹,并使用在该文件夹下创建的子文件夹来保存应用程序的数据。它是在创建时设置的TDataModule
:
procedure TAppData.Create(Sender.TObject);
begin
// DataPath is a property of the datamodule, declared as a string
// CSIDL_LOCAL_APPDATA is the local non-roaming profile folder.
// CSIDL_APPDATA is for the local roaming profile folder, and is more typically used
DataPath := GetFolderLocation(Application.Handle, CSIDL_LOCAL_APPDATA);
DataPath := IncludeTrailingPathDelimiter(DataPath) + 'MyApp\';
end;
See MSDN 的文档页面关于各种含义CSIDL_
or FOLDERID_
价值观。这FOLDERID_
值类似,但仅在 Vista 及更高版本上可用,并与SHGetKnownFolderIDList.
对于你们这些人not愿意无视 MS 的警告SHGetSpecialFolderPath
不受支持,这是一个替代版本GetFolderLocation
using SHGetFolderPath
,这是首选:
uses
ShlObj, SHFolder, ActiveX, Windows;
function GetFolderLocation(Handle: HWnd; Folder: Integer): string;
begin
Result := '';
SetLength(Result, MAX_PATH);
if not Succeeded(SHGetFolderPath(Handle, Folder, 0, 0, PChar(Result))) then
RaiseLastOSError();
end;
最后,对于那些只使用 Vista 及更高版本的人,这里有一个使用的示例SH获取已知文件夹路径- 请注意,这在 Delphi 的 XE 之前版本中不可用(据我所知,可能是 2009 年或 2010 年),您需要使用已知文件夹ID值而不是CSIDL_
, like FOLDERID_LocalAppData
:
uses
ShlObj, ActiveX, KnownFolders;
// Tested on XE2, VCL forms application, Win32 target, on Win7 64-bit Pro
function GetFolderLocation(const Folder: TGuid): string;
var
Buf: PWideChar;
begin
Result := '';
if Succeeded(SHGetKnownFolderPath(Folder, 0, 0, Buf)) then
begin
Result := Buf;
CoTaskMemFree(Buf);
end
else
RaiseLastOSError();
end;