gpt4 book ai didi

c++ - 如何使用 C++ 在 %APPDATA% 中创建一个新文件夹?

转载 作者:行者123 更新时间:2023-11-28 06:45:36 25 4
gpt4 key购买 nike

我尝试包含 IOUtils 库并使用 CSIDL 命令,但它不起作用...

这是执行此操作的代码部分:

//------------------- Includes -----------------------
#include <fmx.h>
#include <IOUtils.hpp>
#pragma hdrstop

#include "Unit1.h"
#include "Unit2.h"
#include "Unit3.h"
//---------------------- end ------------------------
//---- On Form Show (bugged event: It doesn't create the needed folder) ----

void __fastcall TfrmInicio::FormShow(TObject *Sender)
{
if (TDirectory::Exists("CSIDL_APPDATA\\Nintersoft\\Ninterfin")) {
if (FileExists("CSIDL_APPDATA\\Nintersoft\\Ninterfin\\Inf.nf")) {
mmInfo->Lines->LoadFromFile("CSIDL_APPDATA\\Nintersoft\\Ninterfin\\Inf.nf");
}
}
else {
TDirectory::CreateDirectory("CSIDL_APPDATA\\Nintersoft\\Ninterfin");
}
}

//--------------------------------- end ------------------------------------

我希望你能帮助我...非常感谢XD

最佳答案

您不应该将“CSIDL_APPDATA”本身直接硬编码到您的目录路径字符串中。 CSIDL_APPDATA 是一个虚拟文件夹的 ID 号(特别是 26),您必须在运行时使用 Win32 API 动态解析它,例如:

void __fastcall TfrmInicio::FormShow(TObject *Sender)
{
WCHAR szPath[MAX_PATH+1] = {0};
if (SUCCEEDED(SHGetFolderPathW(FmxHandleToHWND(Handle), CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, szPath)))
{
String DirPath = TPath::Combine(szPath, L"Nintersoft\\Ninterfin");
TDirectory::CreateDirectory(DirPath);

String FileName = TPath::Combine(DirPath, L"Inf.nf");
if (TFile::Exists(FileName))
mmInfo->Lines->LoadFromFile(FileName);
}
}

或者,仅在 Vista 和更高版本上,使用 SHGetKnownFolderPath() 代替:

void __fastcall TfrmInicio::FormShow(TObject *Sender)
{
PWSTR pszPath;
if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, NULL, &pszPath)))
{
String DirPath = TPath::Combine(pszPath, L"Nintersoft\\Ninterfin");
CoTaskMemFree(pszPath);

TDirectory::CreateDirectory(DirPath);

String FileName = TPath::Combine(DirPath, L"Inf.nf");
if (TFile::Exists(FileName))
mmInfo->Lines->LoadFromFile(FileName);
}
}

或者,使用 Sysutils::GetEnvironmentVariable() 检索 %APPDATA% 的值,而不是使用 CSIDL已知文件夹 ID:

void __fastcall TfrmInicio::FormShow(TObject *Sender)
{
String DirPath = TPath::Combine(Sysutils::GetEnvironmentVariable(L"APPDATA"), L"Nintersoft\\Ninterfin");
TDirectory::CreateDirectory(DirPath);

String FileName = TPath::Combine(DirPath, L"Inf.nf");
if (TFile::Exists(FileName))
mmInfo->Lines->LoadFromFile(FileName);
}

关于c++ - 如何使用 C++ 在 %APPDATA% 中创建一个新文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25070786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com