Search code examples
c++winapiappdata

C++ CreateDirectory() not working with APPDATA


I want to create a directory inside the %APPDATA% folder. I am using CreateDirectory() for this and it doesn't work. I debugged the code and it seems like the path is correct, but I can't see a new directory in my the APPDATA.

My code for creating dit in appdata:

void setAppDataDir(std::string name)
{
    char* path;
    size_t len;
    _dupenv_s(&path, &len, "APPDATA");
    AppDataPath = path;
    AppDataPath += "\\"+name;

    createDir(this->AppDataPath.c_str());
}

void createDir(const char* path)
{
    assert(CreateDirectory((PCWSTR)path, NULL) || ERROR_ALREADY_EXISTS == GetLastError()); // no exception here
}

This is how I call the function:

setAppDataDir("thisistest");

I use Visual Studio 2019 and the debugger tells me, that path is C:\\Users\\Micha\AppData\Roaming\\thisistest

What am I doing wrong?


Solution

  • CreateDirectory() is a macro that expands to CreateDirectoryW() in your case, which requires strings in UTF-16LE encoding (wchar_t*). You are casting the const char* path param to PCWSTR (const wchar_t*):

    CreateDirectory((PCWSTR)path, NULL) ...
    

    But you are not converting that string into a UTF-16LE string.

    So, you need to convert your path into a wchar_t* string. There are some methods to do it, see Convert char * to LPWSTR.