Question

I am trying to remove short name of a file in NTFS. I am testing it on Windows 7. I am running my process as an administrator.

Here is my code:

    HANDLE hFile;
    DWORD error = NO_ERROR;

    hFile = fh = CreateFileA(name, 
                    GENERIC_ALL,
                    FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE, 
                    NULL, 
                    OPEN_EXISTING,
                    FILE_FLAG_BACKUP_SEMANTICS,
                    NULL);
    if(hFile == NULL || hFile == INVALID_HANDLE_VALUE)
    {
        error = GetLastError();
        if(GetLastError() == ERROR_ACCESS_DENIED)
            printf("File Access Denied.\n");
        if(GetLastError() == ERROR_FILE_NOT_FOUND)
            printf("File not found.\n");
        return error;
    }
    SetLastError(NO_ERROR);

    ModifyPrivilege(SE_RESTORE_NAME, TRUE);

    SetLastError(NO_ERROR);
    SetFileShortNameW(hFile, L""); // As per MSDN, It will work only in windows 7 and above
    error = GetlastError(); // returns 1314 error  
    ModifyPrivilege(SE_RESTORE_NAME, FALSE);

    CloseHandle(hFile);

Code for ModifyPrivilege() is same as on MSDN:

http://msdn.microsoft.com/en-us/library/windows/desktop/aa387705(v=vs.85).aspx

I am making sure that I have SE_RESTORE_NAME privilege (using process explorer for this). Above code does not generate any error but when I look at mft record of the file in hex editor, Short file name is still there i.e. MFT record has two $30 File name attributes, one for full name and other for short name.

I want to know if my code is wrong or some thing else that I have to do? Why does not SetFileShortNameEx function does not any effect in this case?

Was it helpful?

Solution

You need to add the privilege before you call CreateFile.


Your error handling is a bit messed up too. There's no need for any calls to SetLastError. You simply need to check the return values of the API call before you call GetLastError. Only call GetLastError if the docs say that it has meaning. In the case of SetFileShortName, as is the case for many API calls, you only call GetLastError when the API call returns FALSE. So you should write:

if (!SetFileShortNameW(hFile, L""))
{
    error = GetLastError();
    // ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top