File Management Functions


GetFullPathName Function

Retrieves the full path and file name of the specified file.

To perform this operation as a transacted operation, use the GetFullPathNameTransacted function.

For more information about file and path names, see File Names, Paths, and Namespaces.

Note  The GetFullPathName function is not recommended for multithreaded applications or shared library code. For more information, see the Remarks section.

Syntax

C++
DWORD WINAPI GetFullPathName(
  __in   LPCTSTR lpFileName,
  __in   DWORD nBufferLength,
  __out  LPTSTR lpBuffer,
  __out  LPTSTR *lpFilePart
);

Parameters

lpFileName [in]

The name of the file.

This parameter can be a short (the 8.3 form) or long file name. This string can also be a share or volume name.

In the ANSI version of this function, the name is limited to MAX_PATH characters. To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path. For more information, see Naming a File.

nBufferLength [in]

The size of the buffer to receive the null-terminated string for the drive and path, in TCHARs.

lpBuffer [out]

A pointer to a buffer that receives the null-terminated string for the drive and path.

lpFilePart [out]

A pointer to a buffer that receives the address (within lpBuffer) of the final file name component in the path.

This parameter can be NULL.

If lpBuffer refers to a directory and not a file, lpFilePart receives zero.

Return Value

If the function succeeds, the return value is the length, in TCHARs, of the string copied to lpBuffer, not including the terminating null character.

If the lpBuffer buffer is too small to contain the path, the return value is the size, in TCHARs, of the buffer that is required to hold the path and the terminating null character.

If the function fails for any other reason, the return value is zero. To get extended error information, call GetLastError.

Remarks

GetFullPathName merges the name of the current drive and directory with a specified file name to determine the full path and file name of a specified file. It also calculates the address of the file name portion of the full path and file name

This function does not verify that the resulting path and file name are valid, or that they see an existing file on the associated volume.

Note that the lpFilePart parameter does not require string buffer space, but only enough for a single address. This is because it simply returns an address within the buffer that already exists for lpBuffer.

Share and volume names are valid input for lpFileName. For example, the following list identities the returned path and file names if test-2 is a remote computer and U: is a network mapped drive:

  • If you specify "\\test-2\q$\lh" the path returned is "\\test-2\q$\lh "
  • If you specify "\\?\UNC\test-2\q$\lh" the path returned is "\\?\UNC\test-2\q$\lh"
  • If you specify "U:" the path returned is "U:\"

GetFullPathName does not convert the specified file name, lpFileName. If the specified file name exists, you can use GetLongPathName or GetShortPathName to convert to long or short path names, respectively.

If the return value is greater than the value specified in nBufferLength, you can call the function again with a buffer that is large enough to hold the path. For an example of this case in addition to using zero-length buffer for dynamic allocation, see the Example Code section.

Note  Although the return value in this case is a length that includes the terminating null character, the return value on success does not include the terminating null character in the count.

Multithreaded applications and shared library code should not use the GetFullPathName function and should avoid using relative path names. The current directory state written by the SetCurrentDirectory function is stored as a global variable in each process, therefore multithreaded applications cannot reliably use this value without possible data corruption from other threads that may also be reading or setting this value. This limitation also applies to the SetCurrentDirectory and GetCurrentDirectory functions. The exception being when the application is guaranteed to be running in a single thread, for example parsing file names from the command line argument string in the main thread prior to creating any additional threads. Using relative path names in multithreaded applications or shared library code can yield unpredictable results and is not supported.

Examples

The following C++ example shows a basic use of GetFullPathName, GetLongPathName, and GetShortPathName. For another example using dynamic allocation, see GetShortPathName.

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

#define BUFSIZE 4096
#define LONG_DIR_NAME TEXT("c:\\longdirectoryname")

void _tmain(int argc, TCHAR *argv[])
{
    DWORD  retval=0;
    BOOL   success; 
    TCHAR  buffer[BUFSIZE]=TEXT(""); 
    TCHAR  buf[BUFSIZE]=TEXT(""); 
    TCHAR** lppPart={NULL};

   if( argc != 2 )
   {
      _tprintf(TEXT("Usage: %s [file]\n"), argv[0]);
      return;
   }

// Retrieve the full path name for a file. 
// The file does not need to exist.

    retval = GetFullPathName(argv[1],
                 BUFSIZE,
                 buffer,
                 lppPart);
    
    if (retval == 0) 
    {
        // Handle an error condition.
        printf ("GetFullPathName failed (%d)\n", GetLastError());
        return;
    }
    else 
    {
        _tprintf(TEXT("The full path name is:  %s\n"), buffer);
        if (lppPart != NULL && *lppPart != 0)
        {
            _tprintf(TEXT("The final component in the path name is:  %s\n"), *lppPart);
        }
    }


// Create a long directory name for use with the next two examples.

    success = CreateDirectory(LONG_DIR_NAME,
                              NULL);

    if (!success)
    {
        // Handle an error condition.
        printf ("CreateDirectory failed (%d)\n", GetLastError());
        return;
    }


// Retrieve the short path name.  

    retval = GetShortPathName(LONG_DIR_NAME,
                  buf,
                  BUFSIZE);

    if (retval == 0) 
    {
        // Handle an error condition.
         printf ("GetShortPathName failed (%d)\n", GetLastError());
         return;
    }
    else _tprintf(TEXT("The short name for %s is %s\n"), 
                  LONG_DIR_NAME, buf);


// Retrieve the long path name.  

    retval = GetLongPathName(buf,
              buffer,
              BUFSIZE);

    if (retval == 0) 
    {
        // Handle an error condition.
         printf ("GetLongPathName failed (%d)\n", GetLastError());
         return;
    }
    else _tprintf(TEXT("The long name for %s is %s\n"), buf, buffer);

// Clean up the directory.

    success = RemoveDirectory(LONG_DIR_NAME);
    if (!success)
    {
        // Handle an error condition.
        printf ("RemoveDirectory failed (%d)\n", GetLastError());
        return;
    }
}

Requirements

Minimum supported clientWindows 2000 Professional
Minimum supported serverWindows 2000 Server
HeaderWinBase.h (include Windows.h)
LibraryKernel32.lib
DLLKernel32.dll
Unicode and ANSI namesGetFullPathNameW (Unicode) and GetFullPathNameA (ANSI)

See Also

File Management Functions
GetFullPathNameTransacted
GetLongPathName
GetShortPathName
GetTempPath
SearchPath

Send comments about this topic to Microsoft

Build date: 11/12/2009

Tags :


Community Content

Thomas Lee
Do not rely on canonicalization of a path using this function to make security related decisions.

GetFullPathName does not do any validation that the resulting path is valid.

In general, attempting to enforce security by checking names and paths is fraught with danger.

Instead, use ACLs, impersonation and AccessCheck to enforce your application’s security policies.


Gideon7
GetFullPathName known issues

Known Issues

  • GetFullPathName does not consistently strip trailing backslashes from non-folders, nor does it append backslashes to folders.
  • In the ANSI version the argument nBufferLength must always be at least MAX_PATH (260). Otherwise a path length longer than nBufferLength will corrupt the return buffer (lpBuffer) and possibly overrun the stack/heap.

The issues listed above have been observed on XP.


Thomas Lee
Description incorrect for directories
The text says that the "file part" pointer is set ro zero for directories. This is incorrect, at least on XP. It only works that way if the name specified ends with a trailing backslash, otherwise "the file part" points to the last directory, e.g. if C:\A\B\C is specified, it points to C, even if C is a directory.
Tags : contentbug?

Tabas
If a file has two or more dots in the name.. a FileNotFound exception is thrown
If a file has two or more dots in the name.. the FileNotFound exception is thwon and the application attempt to quit. This issue is can be reproduced here:

using System;
using System.IO;
class FileNotFoundExample {
public static void Main () {
string badPath = "/Eccma/examples/FileTest.cs";
string goodPath = "/Ecma/examples2/FileTest.cs";
try {
File.Copy(badPath,goodPath);
}
catch (FileNotFoundException e) {
Console.WriteLine("Caught: {0}",e.ToString());
}
}
}
The output is

Caught: System.IO.FileNotFoundException: Could not find file "/Eccma/examples/FileTest.cs".
File name: "/Eccma/examples/FileTest.cs"
at System.IO.__Error.WinIOError(Int32 errorCode, String str)
at System.IO.File.InternalCopy(String sourceFileName, String destFileName,
Boolean overwrite)
at FileNotFoundExample.Main()


or attempting get the FileInfo using the following code:

FileInfo newFileInfo = new FileInfo(_fileNormalize);

with a file in an invalid file name like MR CESAR QÜEB 19.08.2009.DOC.
Tags :

Page view tracker