Andreas
Andreas

Reputation: 10037

How can I get the current directory with correct spelling?

I can get the path of the current directory using GetCurrentDirectory() but it always seems to inherit the spelling of PowerShell's current directory. For example, let's suppose I have a directory structure named Test\MyProgram on volume D:. Now if I do this in PowerShell:

 cd D:/test/myprogram
 ./myprogram

Then GetCurrentDirectory() will return D:\test\myprogram as the current directory because that's what I passed to cd but as described above, it is D:\Test\MyProgram in reality.

Of course, upper and lower case characters don't make a difference on Windows, but still: How can I get the real name of the current directory, with the correct spelling?

Upvotes: 1

Views: 308

Answers (2)

RbMm
RbMm

Reputation: 33706

only the file system know how file names stored internally. so only way - open handle for path and then query file system about path. say via GetFinalPathNameByHandleW api. but note - you at begin need have correct path - otherwise you fail open file. so i think usually no sense do this

// here path returned by call GetCurrentDirectoryW

HANDLE hFile = CreateFileW(path, 0, 0, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);

if (hFile != INVALID_HANDLE_VALUE)
{
    if (PWSTR szFilePath = new WCHAR[MAXSHORT])
    {
        if (GetFinalPathNameByHandle(hFile, szFilePath, MAXSHORT, FILE_NAME_NORMALIZED))
        {
            DbgPrint("%S\n", szFilePath);
        }
        delete [] szFilePath;
    }
    CloseHandle(hFile);
}

also note that we can use FILE_NAME_OPENED instead FILE_NAME_NORMALIZED. difference here - that in case we use FILE_NAME_NORMALIZED - the GetFinalPathNameByHandleW do extra query to file system - FileNormalizedNameInformation asked. This information class is implemented on ReFS and NTFS file systems. Other file systems return STATUS_INVALID_DEVICE_REQUEST. if say true i dont know when FileNormalizedNameInformation return different name than FileNameInformation. so on practice call with FILE_NAME_OPENED work bit faster and give the same result as FILE_NAME_NORMALIZED

Upvotes: 3

David Heffernan
David Heffernan

Reputation: 612804

Call GetFileInformationByHandleEx passing a file handle and FileNameInfo as the FileInformationClass argument. You'll need to do this for each component on your path.

Upvotes: 0

Related Questions