Windows application directory path

File path formats on Windows systems

Members of many of the types in the System.IO namespace include a path parameter that lets you specify an absolute or relative path to a file system resource. This path is then passed to Windows file system APIs. This topic discusses the formats for file paths that you can use on Windows systems.

Traditional DOS paths

A standard DOS path can consist of three components:

  • A volume or drive letter followed by the volume separator ( : ).
  • A directory name. The directory separator character separates subdirectories within the nested directory hierarchy.
  • An optional filename. The directory separator character separates the file path and the filename.

If all three components are present, the path is absolute. If no volume or drive letter is specified and the directory name begins with the directory separator character, the path is relative from the root of the current drive. Otherwise, the path is relative to the current directory. The following table shows some possible directory and file paths.

Path Description
C:\Documents\Newsletters\Summer2018.pdf An absolute file path from the root of drive C: .
\Program Files\Custom Utilities\StringFinder.exe An absolute path from the root of the current drive.
2018\January.xlsx A relative path to a file in a subdirectory of the current directory.
..\Publications\TravelBrochure.pdf A relative path to file in a directory that is a peer of the current directory.
C:\Projects\apilibrary\apilibrary.sln An absolute path to a file from the root of drive C: .
C:Projects\apilibrary\apilibrary.sln A relative path from the current directory of the C: drive.

Note the difference between the last two paths. Both specify the optional volume specifier ( C: in both cases), but the first begins with the root of the specified volume, whereas the second does not. As result, the first is an absolute path from the root directory of drive C: , whereas the second is a relative path from the current directory of drive C: . Use of the second form when the first is intended is a common source of bugs that involve Windows file paths.

You can determine whether a file path is fully qualified (that is, it the path is independent of the current directory and does not change when the current directory changes) by calling the Path.IsPathFullyQualified method. Note that such a path can include relative directory segments ( . and .. ) and still be fully qualified if the resolved path always points to the same location.

The following example illustrates the difference between absolute and relative paths. It assumes that the directory D:\FY2018\ exists, and that you haven’t set any current directory for D:\ from the command prompt before running the example.

If you would like to see code comments translated to languages other than English, let us know in this GitHub discussion issue.

UNC paths

Universal naming convention (UNC) paths, which are used to access network resources, have the following format:

  • A server or host name, which is prefaced by \\ . The server name can be a NetBIOS machine name or an IP/FQDN address (IPv4 as well as v6 are supported).
  • A share name, which is separated from the host name by \ . Together, the server and share name make up the volume.
  • A directory name. The directory separator character separates subdirectories within the nested directory hierarchy.
  • An optional filename. The directory separator character separates the file path and the filename.

The following are some examples of UNC paths:

Path Description
\\system07\C$\ The root directory of the C: drive on system07 .
\\Server2\Share\Test\Foo.txt The Foo.txt file in the Test directory of the \\Server2\Share volume.

UNC paths must always be fully qualified. They can include relative directory segments ( . and .. ), but these must be part of a fully qualified path. You can use relative paths only by mapping a UNC path to a drive letter.

DOS device paths

The Windows operating system has a unified object model that points to all resources, including files. These object paths are accessible from the console window and are exposed to the Win32 layer through a special folder of symbolic links that legacy DOS and UNC paths are mapped to. This special folder is accessed via the DOS device path syntax, which is one of:

In addition to identifying a drive by its drive letter, you can identify a volume by using its volume GUID. This takes the form:

DOS device path syntax is supported on .NET implementations running on Windows starting with .NET Core 1.1 and .NET Framework 4.6.2.

The DOS device path consists of the following components:

The device path specifier ( \\.\ or \\?\ ), which identifies the path as a DOS device path.

The \\?\ is supported in all versions of .NET Core and .NET 5+ and in .NET Framework starting with version 4.6.2.

A symbolic link to the «real» device object (C: in the case of a drive name, or Volume in the case of a volume GUID).

The first segment of the DOS device path after the device path specifier identifies the volume or drive. (For example, \\?\C:\ and \\.\BootPartition\ .)

There is a specific link for UNCs that is called, not surprisingly, UNC . For example:

For device UNCs, the server/share portion forms the volume. For example, in \\?\server1\e:\utilities\\filecomparer\ , the server/share portion is server1\utilities . This is significant when calling a method such as Path.GetFullPath(String, String) with relative directory segments; it is never possible to navigate past the volume.

DOS device paths are fully qualified by definition. Relative directory segments ( . and .. ) are not allowed. Current directories never enter into their usage.

Example: Ways to refer to the same file

The following example illustrates some of the ways in which you can refer to a file when using the APIs in the System.IO namespace. The example instantiates a FileInfo object and uses its Name and Length properties to display the filename and the length of the file.

Path normalization

Almost all paths passed to Windows APIs are normalized. During normalization, Windows performs the following steps:

  • Identifies the path.
  • Applies the current directory to partially qualified (relative) paths.
  • Canonicalizes component and directory separators.
  • Evaluates relative directory components ( . for the current directory and .. for the parent directory).
  • Trims certain characters.

This normalization happens implicitly, but you can do it explicitly by calling the Path.GetFullPath method, which wraps a call to the GetFullPathName() function. You can also call the Windows GetFullPathName() function directly using P/Invoke.

Identify the path

The first step in path normalization is identifying the type of path. Paths fall into one of a few categories:

  • They are device paths; that is, they begin with two separators and a question mark or period ( \\? or \\. ).
  • They are UNC paths; that is, they begin with two separators without a question mark or period.
  • They are fully qualified DOS paths; that is, they begin with a drive letter, a volume separator, and a component separator ( C:\ ).
  • They designate a legacy device ( CON , LPT1 ).
  • They are relative to the root of the current drive; that is, they begin with a single component separator ( \ ).
  • They are relative to the current directory of a specified drive; that is, they begin with a drive letter, a volume separator, and no component separator ( C: ).
  • They are relative to the current directory; that is, they begin with anything else ( temp\testfile.txt ).

The type of the path determines whether or not a current directory is applied in some way. It also determines what the «root» of the path is.

Handle legacy devices

If the path is a legacy DOS device such as CON , COM1 , or LPT1 , it is converted into a device path by prepending \\.\ and returned.

A path that begins with a legacy device name is always interpreted as a legacy device by the Path.GetFullPath(String) method. For example, the DOS device path for CON.TXT is \\.\CON , and the DOS device path for COM1.TXT\file1.txt is \\.\COM1 .

Apply the current directory

If a path isn’t fully qualified, Windows applies the current directory to it. UNCs and device paths do not have the current directory applied. Neither does a full drive with separator C:\ .

If the path starts with a single component separator, the drive from the current directory is applied. For example, if the file path is \utilities and the current directory is C:\temp\ , normalization produces C:\utilities .

If the path starts with a drive letter, volume separator, and no component separator, the last current directory set from the command shell for the specified drive is applied. If the last current directory was not set, the drive alone is applied. For example, if the file path is D:sources , the current directory is C:\Documents\ , and the last current directory on drive D: was D:\sources\ , the result is D:\sources\sources . These «drive relative» paths are a common source of program and script logic errors. Assuming that a path beginning with a letter and a colon isn’t relative is obviously not correct.

If the path starts with something other than a separator, the current drive and current directory are applied. For example, if the path is filecompare and the current directory is C:\utilities\ , the result is C:\utilities\filecompare\ .

Relative paths are dangerous in multithreaded applications (that is, most applications) because the current directory is a per-process setting. Any thread can change the current directory at any time. Starting with .NET Core 2.1, you can call the Path.GetFullPath(String, String) method to get an absolute path from a relative path and the base path (the current directory) that you want to resolve it against.

Canonicalize separators

All forward slashes ( / ) are converted into the standard Windows separator, the back slash ( \ ). If they are present, a series of slashes that follow the first two slashes are collapsed into a single slash.

Evaluate relative components

As the path is processed, any components or segments that are composed of a single or a double period ( . or .. ) are evaluated:

For a single period, the current segment is removed, since it refers to the current directory.

For a double period, the current segment and the parent segment are removed, since the double period refers to the parent directory.

Parent directories are only removed if they aren’t past the root of the path. The root of the path depends on the type of path. It is the drive ( C:\ ) for DOS paths, the server/share for UNCs ( \\Server\Share ), and the device path prefix for device paths ( \\?\ or \\.\ ).

Trim characters

Along with the runs of separators and relative segments removed earlier, some additional characters are removed during normalization:

If a segment ends in a single period, that period is removed. (A segment of a single or double period is normalized in the previous step. A segment of three or more periods is not normalized and is actually a valid file/directory name.)

If the path doesn’t end in a separator, all trailing periods and spaces (U+0020) are removed. If the last segment is simply a single or double period, it falls under the relative components rule above.

This rule means that you can create a directory name with a trailing space by adding a trailing separator after the space.

You should never create a directory or filename with a trailing space. Trailing spaces can make it difficult or impossible to access a directory, and applications commonly fail when attempting to handle directories or files whose names include trailing spaces.

Skip normalization

Normally, any path passed to a Windows API is (effectively) passed to the GetFullPathName function and normalized. There is one important exception: a device path that begins with a question mark instead of a period. Unless the path starts exactly with \\?\ (note the use of the canonical backslash), it is normalized.

Why would you want to skip normalization? There are three major reasons:

To get access to paths that are normally unavailable but are legal. A file or directory called hidden. , for example, is impossible to access in any other way.

To improve performance by skipping normalization if you’ve already normalized.

On .NET Framework only, to skip the MAX_PATH check for path length to allow for paths that are greater than 259 characters. Most APIs allow this, with some exceptions.

.NET Core and .NET 5+ handles long paths implicitly and does not perform a MAX_PATH check. The MAX_PATH check applies only to .NET Framework.

Skipping normalization and max path checks is the only difference between the two device path syntaxes; they are otherwise identical. Be careful with skipping normalization, since you can easily create paths that are difficult for «normal» applications to deal with.

Paths that start with \\?\ are still normalized if you explicitly pass them to the GetFullPathName function.

You can pass paths of more than MAX_PATH characters to GetFullPathName without \\?\ . It supports arbitrary length paths up to the maximum string size that Windows can handle.

Case and the Windows file system

A peculiarity of the Windows file system that non-Windows users and developers find confusing is that path and directory names are case-insensitive. That is, directory and file names reflect the casing of the strings used when they are created. For example, the method call

Naming Files, Paths, and Namespaces

All file systems supported by Windows use the concept of files and directories to access data stored on a disk or device. Windows developers working with the Windows APIs for file and device I/O should understand the various rules, conventions, and limitations of names for files and directories.

Data can be accessed from disks, devices, and network shares using file I/O APIs. Files and directories, along with namespaces, are part of the concept of a path, which is a string representation of where to get the data regardless if it’s from a disk or a device or a network connection for a specific operation.

Some file systems, such as NTFS, support linked files and directories, which also follow file naming conventions and rules just as a regular file or directory would. For additional information, see Hard Links and Junctions and Reparse Points and File Operations.

For additional information, see the following subsections:

To learn about configuring Windows 10 to support long file paths, see Maximum Path Length Limitation.

File and Directory Names

All file systems follow the same general naming conventions for an individual file: a base file name and an optional extension, separated by a period. However, each file system, such as NTFS, CDFS, exFAT, UDFS, FAT, and FAT32, can have specific and differing rules about the formation of the individual components in the path to a directory or file. Note that a directory is simply a file with a special attribute designating it as a directory, but otherwise must follow all the same naming rules as a regular file. Because the term directory simply refers to a special type of file as far as the file system is concerned, some reference material will use the general term file to encompass both concepts of directories and data files as such. Because of this, unless otherwise specified, any naming or usage rules or examples for a file should also apply to a directory. The term path refers to one or more directories, backslashes, and possibly a volume name. For more information, see the Paths section.

Character count limitations can also be different and can vary depending on the file system and path name prefix format used. This is further complicated by support for backward compatibility mechanisms. For example, the older MS-DOS FAT file system supports a maximum of 8 characters for the base file name and 3 characters for the extension, for a total of 12 characters including the dot separator. This is commonly known as an 8.3 file name. The Windows FAT and NTFS file systems are not limited to 8.3 file names, because they have long file name support, but they still support the 8.3 version of long file names.

Naming Conventions

The following fundamental rules enable applications to create and process valid names for files and directories, regardless of the file system:

Use a period to separate the base file name from the extension in the name of a directory or file.

Use a backslash (\) to separate the components of a path. The backslash divides the file name from the path to it, and one directory name from another directory name in a path. You cannot use a backslash in the name for the actual file or directory because it is a reserved character that separates the names into components.

Use a backslash as required as part of volume names, for example, the «C:\» in «C:\path\file» or the «\\server\share» in «\\server\share\path\file» for Universal Naming Convention (UNC) names. For more information about UNC names, see the Maximum Path Length Limitation section.

Do not assume case sensitivity. For example, consider the names OSCAR, Oscar, and oscar to be the same, even though some file systems (such as a POSIX-compliant file system) may consider them as different. Note that NTFS supports POSIX semantics for case sensitivity but this is not the default behavior. For more information, see CreateFile.

Volume designators (drive letters) are similarly case-insensitive. For example, «D:\» and «d:\» refer to the same volume.

Use any character in the current code page for a name, including Unicode characters and characters in the extended character set (128–255), except for the following:

The following reserved characters:

  • (greater than)
  • : (colon)
  • » (double quote)
  • / (forward slash)
  • \ (backslash)
  • | (vertical bar or pipe)
  • ? (question mark)
  • * (asterisk)

Integer value zero, sometimes referred to as the ASCII NUL character.

Characters whose integer representations are in the range from 1 through 31, except for alternate data streams where these characters are allowed. For more information about file streams, see File Streams.

Any other character that the target file system does not allow.

Use a period as a directory component in a path to represent the current directory, for example «.\temp.txt». For more information, see Paths.

Use two consecutive periods (..) as a directory component in a path to represent the parent of the current directory, for example «..\temp.txt». For more information, see Paths.

Do not use the following reserved names for the name of a file:

CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9. Also avoid these names followed immediately by an extension; for example, NUL.txt is not recommended. For more information, see Namespaces.

Do not end a file or directory name with a space or a period. Although the underlying file system may support such names, the Windows shell and user interface does not. However, it is acceptable to specify a period as the first character of a name. For example, «.temp».

Short vs. Long Names

A long file name is considered to be any file name that exceeds the short MS-DOS (also called 8.3) style naming convention. When you create a long file name, Windows may also create a short 8.3 form of the name, called the 8.3 alias or short name, and store it on disk also. This 8.3 aliasing can be disabled for performance reasons either systemwide or for a specified volume, depending on the particular file system.

Windows ServerВ 2008, WindowsВ Vista, Windows ServerВ 2003 and WindowsВ XP: 8.3 aliasing cannot be disabled for specified volumes until WindowsВ 7 and Windows ServerВ 2008В R2.

On many file systems, a file name will contain a tilde (

) within each component of the name that is too long to comply with 8.3 naming rules.

Not all file systems follow the tilde substitution convention, and systems can be configured to disable 8.3 alias generation even if they normally support it. Therefore, do not make the assumption that the 8.3 alias already exists on-disk.

To request 8.3 file names, long file names, or the full path of a file from the system, consider the following options:

  • To get the 8.3 form of a long file name, use the GetShortPathName function.
  • To get the long file name version of a short name, use the GetLongPathName function.
  • To get the full path to a file, use the GetFullPathName function.

On newer file systems, such as NTFS, exFAT, UDFS, and FAT32, Windows stores the long file names on disk in Unicode, which means that the original long file name is always preserved. This is true even if a long file name contains extended characters, regardless of the code page that is active during a disk read or write operation.

Files using long file names can be copied between NTFS file system partitions and Windows FAT file system partitions without losing any file name information. This may not be true for the older MS-DOS FAT and some types of CDFS (CD-ROM) file systems, depending on the actual file name. In this case, the short file name is substituted if possible.

Paths

The path to a specified file consists of one or more components, separated by a special character (a backslash), with each component usually being a directory name or file name, but with some notable exceptions discussed below. It is often critical to the system’s interpretation of a path what the beginning, or prefix, of the path looks like. This prefix determines the namespace the path is using, and additionally what special characters are used in which position within the path, including the last character.

If a component of a path is a file name, it must be the last component.

Each component of a path will also be constrained by the maximum length specified for a particular file system. In general, these rules fall into two categories: short and long. Note that directory names are stored by the file system as a special type of file, but naming rules for files also apply to directory names. To summarize, a path is simply the string representation of the hierarchy between all of the directories that exist for a particular file or directory name.

Fully Qualified vs. Relative Paths

For Windows API functions that manipulate files, file names can often be relative to the current directory, while some APIs require a fully qualified path. A file name is relative to the current directory if it does not begin with one of the following:

  • A UNC name of any format, which always start with two backslash characters («\\»). For more information, see the next section.
  • A disk designator with a backslash, for example «C:\» or «d:\».
  • A single backslash, for example, «\directory» or «\file.txt». This is also referred to as an absolute path.

If a file name begins with only a disk designator but not the backslash after the colon, it is interpreted as a relative path to the current directory on the drive with the specified letter. Note that the current directory may or may not be the root directory depending on what it was set to during the most recent «change directory» operation on that disk. Examples of this format are as follows:

  • «C:tmp.txt» refers to a file named «tmp.txt» in the current directory on drive C.
  • «C:tempdir\tmp.txt» refers to a file in a subdirectory to the current directory on drive C.

A path is also said to be relative if it contains «double-dots»; that is, two periods together in one component of the path. This special specifier is used to denote the directory above the current directory, otherwise known as the «parent directory». Examples of this format are as follows:

  • «..\tmp.txt» specifies a file named tmp.txt located in the parent of the current directory.
  • «..\..\tmp.txt» specifies a file that is two directories above the current directory.
  • «..\tempdir\tmp.txt» specifies a file named tmp.txt located in a directory named tempdir that is a peer directory to the current directory.

Relative paths can combine both example types, for example «C. \tmp.txt». This is useful because, although the system keeps track of the current drive along with the current directory of that drive, it also keeps track of the current directories in each of the different drive letters (if your system has more than one), regardless of which drive designator is set as the current drive.

Maximum Path Length Limitation

In editions of Windows before Windows 10 version 1607, the maximum length for a path is MAX_PATH, which is defined as 260 characters. In later versions of Windows, changing a registry key or using the Group Policy tool is required to remove the limit. See Maximum Path Length Limitation for full details.

Namespaces

There are two main categories of namespace conventions used in the Windows APIs, commonly referred to as NT namespaces and the Win32 namespaces. The NT namespace was designed to be the lowest level namespace on which other subsystems and namespaces could exist, including the Win32 subsystem and, by extension, the Win32 namespaces. POSIX is another example of a subsystem in Windows that is built on top of the NT namespace. Early versions of Windows also defined several predefined, or reserved, names for certain special devices such as communications (serial and parallel) ports and the default display console as part of what is now called the NT device namespace, and are still supported in current versions of Windows for backward compatibility.

Win32 File Namespaces

The Win32 namespace prefixing and conventions are summarized in this section and the following section, with descriptions of how they are used. Note that these examples are intended for use with the Windows API functions and do not all necessarily work with Windows shell applications such as Windows Explorer. For this reason there is a wider range of possible paths than is usually available from Windows shell applications, and Windows applications that take advantage of this can be developed using these namespace conventions.

For file I/O, the «\\?\» prefix to a path string tells the Windows APIs to disable all string parsing and to send the string that follows it straight to the file system. For example, if the file system supports large paths and file names, you can exceed the MAX_PATH limits that are otherwise enforced by the Windows APIs. For more information about the normal maximum path limitation, see the previous section Maximum Path Length Limitation.

Because it turns off automatic expansion of the path string, the «\\?\» prefix also allows the use of «..» and «.» in the path names, which can be useful if you are attempting to perform operations on a file with these otherwise reserved relative path specifiers as part of the fully qualified path.

Many but not all file I/O APIs support «\\?\»; you should look at the reference topic for each API to be sure.

Note that Unicode APIs should be used to make sure the «\\?\» prefix allows you to exceed the MAX_PATH

Win32 Device Namespaces

The «\\.\» prefix will access the Win32 device namespace instead of the Win32 file namespace. This is how access to physical disks and volumes is accomplished directly, without going through the file system, if the API supports this type of access. You can access many devices other than disks this way (using the CreateFile and DefineDosDevice functions, for example).

For example, if you want to open the system’s serial communications port 1, you can use «COM1» in the call to the CreateFile function. This works because COM1–COM9 are part of the reserved names in the NT namespace, although using the «\\.\» prefix will also work with these device names. By comparison, if you have a 100 port serial expansion board installed and want to open COM56, you cannot open it using «COM56» because there is no predefined NT namespace for COM56. You will need to open it using «\\.\COM56» because «\\.\» goes directly to the device namespace without attempting to locate a predefined alias.

Another example of using the Win32 device namespace is using the CreateFile function with «\\.\PhysicalDiskX» (where X is a valid integer value) or «\\.\CdRomX«. This allows you to access those devices directly, bypassing the file system. This works because these device names are created by the system as these devices are enumerated, and some drivers will also create other aliases in the system. For example, the device driver that implements the name «C:\» has its own namespace that also happens to be the file system.

APIs that go through the CreateFile function generally work with the «\\.\» prefix because CreateFile is the function used to open both files and devices, depending on the parameters you use.

If you’re working with Windows API functions, you should use the «\\.\» prefix to access devices only and not files.

Most APIs won’t support «\\.\»; only those that are designed to work with the device namespace will recognize it. Always check the reference topic for each API to be sure.

NT Namespaces

There are also APIs that allow the use of the NT namespace convention, but the Windows Object Manager makes that unnecessary in most cases. To illustrate, it is useful to browse the Windows namespaces in the system object browser using the Windows Sysinternals WinObj tool. When you run this tool, what you see is the NT namespace beginning at the root, or «\». The subfolder called «Global??» is where the Win32 namespace resides. Named device objects reside in the NT namespace within the «Device» subdirectory. Here you may also find Serial0 and Serial1, the device objects representing the first two COM ports if present on your system. A device object representing a volume would be something like «HarddiskVolume1», although the numeric suffix may vary. The name «DR0» under subdirectory «Harddisk0» is an example of the device object representing a disk, and so on.

To make these device objects accessible by Windows applications, the device drivers create a symbolic link (symlink) in the Win32 namespace, «Global??», to their respective device objects. For example, COM0 and COM1 under the «Global??» subdirectory are simply symlinks to Serial0 and Serial1, «C:» is a symlink to HarddiskVolume1, «Physicaldrive0» is a symlink to DR0, and so on. Without a symlink, a specified device «Xxx» will not be available to any Windows application using Win32 namespace conventions as described previously. However, a handle could be opened to that device using any APIs that support the NT namespace absolute path of the format «\Device\Xxx».

With the addition of multi-user support via Terminal Services and virtual machines, it has further become necessary to virtualize the system-wide root device within the Win32 namespace. This was accomplished by adding the symlink named «GLOBALROOT» to the Win32 namespace, which you can see in the «Global??» subdirectory of the WinObj browser tool previously discussed, and can access via the path «\\?\GLOBALROOT». This prefix ensures that the path following it looks in the true root path of the system object manager and not a session-dependent path.

Читайте также:  После установки windows не работает usb порт
Оцените статью