Question

Le système de fichiers Windows ne respecte pas la casse. Comment, avec un nom de fichier / dossier (par exemple, "un fichier"), je reçois le nom actuel de ce fichier / dossier (par exemple, il devrait renvoyer "SomeFile" si Explorer le montre ainsi)?

Certains moyens que je connais, qui semblent tous très arriérés:

  1. Étant donné le chemin complet, recherchez chaque dossier du chemin (via FindFirstFile). Cela donne les résultats casés appropriés de chaque dossier. À la dernière étape, recherchez le fichier lui-même.
  2. Récupère le nom du fichier à partir de l'handle (comme dans exemple MSDN ). Cela nécessite d'ouvrir un fichier, de créer un mappage de fichier, d'obtenir son nom, d'analyser les noms de périphériques, etc. Très compliqué. Et cela ne fonctionne pas pour les dossiers ou les fichiers de taille zéro.

Me manque-t-il un appel évident à WinAPI? Les plus simples, tels que GetActualPathName () ou GetFullPathName () renvoient le nom en utilisant la casse qui a été transmise (par exemple, renvoie "fichiers de programme" si cela a été passé, même s'il doit s'agir de "Fichiers de programme").

Je recherche une solution native (pas une solution .NET).

Était-ce utile?

La solution

Et je réponds à ma propre question, basée sur réponse originale de cspirz .

Voici une fonction qui donne un chemin absolu, relatif ou réseau, qui renvoie le chemin avec des majuscules / minuscules telles qu’elles seraient affichées sous Windows. Si un composant du chemin n'existe pas, il renverra le chemin transmis à partir de ce point.

Il est très impliqué car il essaie de gérer les chemins réseau et d’autres cas périphériques. Il fonctionne sur des chaînes de caractères larges et utilise std :: wstring. Oui, en théorie, Unicode TCHAR pourrait ne pas être identique à wchar_t; c’est un exercice pour le lecteur:)

std::wstring GetActualPathName( const wchar_t* path )
{
    // This is quite involved, but the meat is SHGetFileInfo

    const wchar_t kSeparator = L'\\';

    // copy input string because we'll be temporary modifying it in place
    size_t length = wcslen(path);
    wchar_t buffer[MAX_PATH];
    memcpy( buffer, path, (length+1) * sizeof(path[0]) );

    size_t i = 0;

    std::wstring result;

    // for network paths (\\server\share\RestOfPath), getting the display
    // name mangles it into unusable form (e.g. "\\server\share" turns
    // into "share on server (server)"). So detect this case and just skip
    // up to two path components
    if( length >= 2 && buffer[0] == kSeparator && buffer[1] == kSeparator )
    {
        int skippedCount = 0;
        i = 2; // start after '\\'
        while( i < length && skippedCount < 2 )
        {
            if( buffer[i] == kSeparator )
                ++skippedCount;
            ++i;
        }

        result.append( buffer, i );
    }
    // for drive names, just add it uppercased
    else if( length >= 2 && buffer[1] == L':' )
    {
        result += towupper(buffer[0]);
        result += L':';
        if( length >= 3 && buffer[2] == kSeparator )
        {
            result += kSeparator;
            i = 3; // start after drive, colon and separator
        }
        else
        {
            i = 2; // start after drive and colon
        }
    }

    size_t lastComponentStart = i;
    bool addSeparator = false;

    while( i < length )
    {
        // skip until path separator
        while( i < length && buffer[i] != kSeparator )
            ++i;

        if( addSeparator )
            result += kSeparator;

        // if we found path separator, get real filename of this
        // last path name component
        bool foundSeparator = (i < length);
        buffer[i] = 0;
        SHFILEINFOW info;

        // nuke the path separator so that we get real name of current path component
        info.szDisplayName[0] = 0;
        if( SHGetFileInfoW( buffer, 0, &info, sizeof(info), SHGFI_DISPLAYNAME ) )
        {
            result += info.szDisplayName;
        }
        else
        {
            // most likely file does not exist.
            // So just append original path name component.
            result.append( buffer + lastComponentStart, i - lastComponentStart );
        }

        // restore path separator that we might have nuked before
        if( foundSeparator )
            buffer[i] = kSeparator;

        ++i;
        lastComponentStart = i;
        addSeparator = true;
    }

    return result;
}

Encore une fois, merci à cspirz de m'avoir dirigé vers SHGetFileInfo.

Autres conseils

Avez-vous essayé d'utiliser SHGetFileInfo?

Il existe une autre solution. Appelez d’abord GetShortPathName () puis GetLongPathName (). Devinez quel caractère sera utilisé alors? ; -)

D'accord, il s'agit de VBScript, mais je suggérerais néanmoins d'utiliser l'objet Scripting.FileSystemObject

Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Dim f
Set f = fso.GetFile("C:\testfile.dat") 'actually named "testFILE.dAt"
wscript.echo f.Name

La réponse que je reçois provient de cet extrait est

testFILE.dAt

J'espère qu'au moins vous diriger dans la bonne direction.

Je viens de constater que le Scripting.FileSystemObject suggéré par @bugmagnet il y a 10 ans est un trésor. Contrairement à mon ancienne méthode, elle fonctionne sur les chemins absolus, relatifs, UNC et très longs (chemin plus long que MAX_PATH ). Honte à moi de ne pas avoir testé sa méthode plus tôt.

Pour référence future, je voudrais présenter ce code qui peut être compilé en mode C et C ++. En mode C ++, le code utilisera STL et ATL. En mode C, vous pouvez clairement voir comment tout fonctionne en arrière-plan.

#include <Windows.h>
#include <objbase.h>
#include <conio.h> // for _getch()

#ifndef __cplusplus
#   include <stdio.h>

#define SafeFree(p, fn) \
    if (p) { fn(p); (p) = NULL; }

#define SafeFreeCOM(p) \
    if (p) { (p)->lpVtbl->Release(p); (p) = NULL; }


static HRESULT CorrectPathCasing2(
    LPCWSTR const pszSrc, LPWSTR *ppszDst)
{
    DWORD const clsCtx = CLSCTX_INPROC_SERVER;
    LCID const lcid = LOCALE_USER_DEFAULT;
    LPCWSTR const pszProgId = L"Scripting.FileSystemObject";
    LPCWSTR const pszMethod = L"GetAbsolutePathName";
    HRESULT hr = 0;
    CLSID clsid = { 0 };
    IDispatch *pDisp = NULL;
    DISPID dispid = 0;
    VARIANT vtSrc = { VT_BSTR };
    VARIANT vtDst = { VT_BSTR };
    DISPPARAMS params = { 0 };
    SIZE_T cbDst = 0;
    LPWSTR pszDst = NULL;

    // CoCreateInstance<IDispatch>(pszProgId, &pDisp)

    hr = CLSIDFromProgID(pszProgId, &clsid);
    if (FAILED(hr)) goto eof;

    hr = CoCreateInstance(&clsid, NULL, clsCtx,
        &IID_IDispatch, (void**)&pDisp);
    if (FAILED(hr)) goto eof;
    if (!pDisp) {
        hr = E_UNEXPECTED; goto eof;
    }

    // Variant<BSTR> vtSrc(pszSrc), vtDst;
    // vtDst = pDisp->InvokeMethod( pDisp->GetIDOfName(pszMethod), vtSrc );

    hr = pDisp->lpVtbl->GetIDsOfNames(pDisp, NULL,
        (LPOLESTR*)&pszMethod, 1, lcid, &dispid);
    if (FAILED(hr)) goto eof;

    vtSrc.bstrVal = SysAllocString(pszSrc);
    if (!vtSrc.bstrVal) {
        hr = E_OUTOFMEMORY; goto eof;
    }
    params.rgvarg = &vtSrc;
    params.cArgs = 1;
    hr = pDisp->lpVtbl->Invoke(pDisp, dispid, NULL, lcid,
        DISPATCH_METHOD, &params, &vtDst, NULL, NULL);
    if (FAILED(hr)) goto eof;
    if (!vtDst.bstrVal) {
        hr = E_UNEXPECTED; goto eof;
    }

    // *ppszDst = AllocWStrCopyBStrFrom(vtDst.bstrVal);

    cbDst = SysStringByteLen(vtDst.bstrVal);
    pszDst = HeapAlloc(GetProcessHeap(),
        HEAP_ZERO_MEMORY, cbDst + sizeof(WCHAR));
    if (!pszDst) {
        hr = E_OUTOFMEMORY; goto eof;
    }
    CopyMemory(pszDst, vtDst.bstrVal, cbDst);
    *ppszDst = pszDst;

eof:
    SafeFree(vtDst.bstrVal, SysFreeString);
    SafeFree(vtSrc.bstrVal, SysFreeString);
    SafeFreeCOM(pDisp);
    return hr;
}

static void Cout(char const *psz)
{
    printf("%s", psz);
}

static void CoutErr(HRESULT hr)
{
    printf("Error HRESULT 0x%.8X!\n", hr);
}

static void Test(LPCWSTR pszPath)
{
    LPWSTR pszRet = NULL;
    HRESULT hr = CorrectPathCasing2(pszPath, &pszRet);
    if (FAILED(hr)) {
        wprintf(L"Input: <%s>\n", pszPath);
        CoutErr(hr);
    }
    else {
        wprintf(L"Was: <%s>\nNow: <%s>\n", pszPath, pszRet);
        HeapFree(GetProcessHeap(), 0, pszRet);
    }
}


#else // Use C++ STL and ATL
#   include <iostream>
#   include <iomanip>
#   include <string>
#   include <atlbase.h>

static HRESULT CorrectPathCasing2(
    std::wstring const &srcPath,
    std::wstring &dstPath)
{
    HRESULT hr = 0;
    CComPtr<IDispatch> disp;
    hr = disp.CoCreateInstance(L"Scripting.FileSystemObject");
    if (FAILED(hr)) return hr;

    CComVariant src(srcPath.c_str()), dst;
    hr = disp.Invoke1(L"GetAbsolutePathName", &src, &dst);
    if (FAILED(hr)) return hr;

    SIZE_T cch = SysStringLen(dst.bstrVal);
    dstPath = std::wstring(dst.bstrVal, cch);
    return hr;
}

static void Cout(char const *psz)
{
    std::cout << psz;
}

static void CoutErr(HRESULT hr)
{
    std::wcout
        << std::hex << std::setfill(L'0') << std::setw(8)
        << "Error HRESULT 0x" << hr << "\n";
}

static void Test(std::wstring const &path)
{
    std::wstring output;
    HRESULT hr = CorrectPathCasing2(path, output);
    if (FAILED(hr)) {
        std::wcout << L"Input: <" << path << ">\n";
        CoutErr(hr);
    }
    else {
        std::wcout << L"Was: <" << path << ">\n"
            << "Now: <" << output << ">\n";
    }
}

#endif


static void TestRoutine(void)
{
    HRESULT hr = CoInitialize(NULL);

    if (FAILED(hr)) {
        Cout("CoInitialize failed!\n");
        CoutErr(hr);
        return;
    }

    Cout("\n[ Absolute Path ]\n");
    Test(L"c:\\uSers\\RayMai\\docuMENTs");
    Test(L"C:\\WINDOWS\\SYSTEM32");

    Cout("\n[ Relative Path ]\n");
    Test(L".");
    Test(L"..");
    Test(L"\\");

    Cout("\n[ UNC Path ]\n");
    Test(L"\\\\VMWARE-HOST\\SHARED FOLDERS\\D\\PROGRAMS INSTALLER");

    Cout("\n[ Very Long Path ]\n");
    Test(L"\\\\?\\C:\\VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
        L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
        L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
        L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
        L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
        L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
        L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
        L"VERYVERYVERYLOOOOOOOONGFOLDERNAME\\"
        L"VERYVERYVERYLOOOOOOOONGFOLDERNAME");

    Cout("\n!! Worth Nothing Behavior !!\n");
    Test(L"");
    Test(L"1234notexist");
    Test(L"C:\\bad\\PATH");

    CoUninitialize();
}

int main(void)
{
    TestRoutine();
    _getch();
    return 0;
}

Capture d'écran:

 screenshot2

Ancienne réponse:

J'ai constaté que FindFirstFile () renverrait le nom de fichier de casse approprié (dernière partie du chemin) dans fd.cFileName . Si nous passons c: \ winDOWs \ exPLORER.exe en tant que premier paramètre de FindFirstFile () , le fd.cFileName serait explorateur .exe comme ceci:

 prouver

Si nous remplaçons la dernière partie du chemin par fd.cFileName , nous aurons la dernière partie à droite; le chemin deviendrait c: \ winDOWs \ explorer.exe .

En supposant que le chemin soit toujours un chemin absolu (aucune modification de la longueur du texte), nous pouvons simplement appliquer cet "algorithme" à chaque partie du chemin (à l'exception de la lettre correspondant au lecteur).

La conversation n’est pas chère, voici le code:

#include <windows.h>
#include <stdio.h>

/*
    c:\windows\windowsupdate.log --> c:\windows\WindowsUpdate.log
*/
static HRESULT MyProcessLastPart(LPTSTR szPath)
{
    HRESULT hr = 0;
    HANDLE hFind = NULL;
    WIN32_FIND_DATA fd = {0};
    TCHAR *p = NULL, *q = NULL;
    /* thePart = GetCorrectCasingFileName(thePath); */
    hFind = FindFirstFile(szPath, &fd);
    if (hFind == INVALID_HANDLE_VALUE) {
        hr = HRESULT_FROM_WIN32(GetLastError());
        hFind = NULL; goto eof;
    }
    /* thePath = thePath.ReplaceLast(thePart); */
    for (p = szPath; *p; ++p);
    for (q = fd.cFileName; *q; ++q, --p);
    for (q = fd.cFileName; *p = *q; ++p, ++q);
eof:
    if (hFind) { FindClose(hFind); }
    return hr;
}

/*
    Important! 'szPath' should be absolute path only.
    MUST NOT SPECIFY relative path or UNC or short file name.
*/
EXTERN_C
HRESULT __stdcall
CorrectPathCasing(
    LPTSTR szPath)
{
    HRESULT hr = 0;
    TCHAR *p = NULL;
    if (GetFileAttributes(szPath) == -1) {
        hr = HRESULT_FROM_WIN32(GetLastError()); goto eof;
    }
    for (p = szPath; *p; ++p)
    {
        if (*p == '\\' || *p == '/')
        {
            TCHAR slashChar = *p;
            if (p[-1] == ':') /* p[-2] is drive letter */
            {
                p[-2] = toupper(p[-2]);
                continue;
            }
            *p = '\0';
            hr = MyProcessLastPart(szPath);
            *p = slashChar;
            if (FAILED(hr)) goto eof;
        }
    }
    hr = MyProcessLastPart(szPath);
eof:
    return hr;
}

int main()
{
    TCHAR szPath[] = TEXT("c:\\windows\\EXPLORER.exe");
    HRESULT hr = CorrectPathCasing(szPath);
    if (SUCCEEDED(hr))
    {
        MessageBox(NULL, szPath, TEXT("Test"), MB_ICONINFORMATION);
    }
    return 0;
}

 prouver 2

Avantages:

  • Le code fonctionne sur toutes les versions de Windows depuis Windows 95.
  • Traitement des erreurs de base.
  • Performances maximales possibles. FindFirstFile () est très rapide, la manipulation directe du tampon le rend encore plus rapide.
  • Seulement C et WinAPI pur. Petite taille d’exécutable.

Inconvénients:

  • Seul le chemin absolu est pris en charge, les autres sont des comportements non définis.
  • Vous ne savez pas s'il s'agit d'un comportement non documenté.
  • Le code est peut-être trop brut et trop complexe pour certaines personnes. Peut-être vous faire flamber.

Raison du style de code:

J'utilise goto pour la gestion des erreurs car j'y étais habitué ( goto est très pratique pour la gestion des erreurs en C). J'utilise pour en boucle pour exécuter des fonctions telles que strcpy et strchr à la volée, car je veux être certain de ce qui a été exécuté.

FindFirstFileNameW fonctionnera avec quelques inconvénients:

  • cela ne fonctionne pas sur les chemins UNC
  • il enlève la lettre de lecteur, vous devez donc la rajouter
  • s'il existe plusieurs liens physiques vers votre fichier, vous devez identifier le bon

Après un test rapide, GetLongPathName () fait ce que tu veux.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top