- NTFS Links, Directory Junctions, and Windows Shortcuts
- NTFS Hard Links
- Programming Considerations
- Creating A Hard Link
- Deleting A Hard Link
- Enumerating Hard Links
- NTFS Symbolic Links
- Programming Considerations
- Reparse Points and Directory Junctions
- Programming Considerations
- Helper Functions
- Creating Directory Junction
- Deleting Directory Junction
- Querying Directory Junction
- Windows Shortcuts
- Programming Considerations
- Creating New Shortcut
- Modifying Existing Shortcut
- Deleting Shortcut
- Desktop? Where Is It?
- Notifying the Explorer
- Downloads
- Create Symbolic Links, Hard Links and Directory Junction Points in Windows with MKLINK
NTFS Links, Directory Junctions, and Windows Shortcuts
A link is basically an alternate name for a file or a directory. In many cases creating a link is preferable to making several copies of the file. Links save disk space, and what is more important, if the file changes afterwards, you will not have to edit a bunch of copies – all the links point to the same file.
If you are familiar with Unix-family operating systems, you must have known what the ln command is. Any BSD or Linux disk contains a lot of links, and the ln command is one of the most commonly used. Windows also supports both hard and soft links, but surprisingly, it provided no command line tool for creating links until Windows 7 .
Windows 7 and later systems include a command-line utility mklink for creating hard links, symbolic links, and directory junctions.
In this article we will show how to create all kinds of links programmatically. If you are not interested in programming and just want to get the utility, skip directly to the download section.
NTFS Hard Links
Hard link uses the same MFT entry as the original file. Adding a hard link creates a new name attribute and increases the hard link count (for a newly created file this count equals to one). Deleting a hard link removes the appropriate name and decreases the hard link count. When the count goes to zero, the system deletes the file, freeing up its allocated disk space and releasing its MFT record. All the name attributes are independent, so deleting, moving, or renaming the file don’t affect other hard links.
In order to get the value of the hard link count, open the file in the FlexHEX editor and select the File Properties page in the Streams pane (the lower left one). If there is any hard link to the file, the Hard Links value will be greater than one (the normal directory record is also counted, so one means no hard links).
Because all the links must refer to the same MFT entry, you cannot create a hard link on a different drive. Another limitation is that only files can be hard-linked, not directories (however soft links to directories are allowed).
Programming Considerations
To get the number of links use the Win32 API function GetFileInformationByHandle. The nNumberOfLinks member of the returned BY_HANDLE_FILE_INFORMATION structure contains the total number of links (a value of 1 means there are no hard links).
Creating A Hard Link
Creating a hard link is simple — just call the Win32 API function CreateHardLink (this function is available in Windows 2000 and later systems).
While the first two arguments are fairly obvious, the third one may be somewhat misleading. Security descriptors belong to files, not to hard links, so if you specify a security attributes in a CreateHardLink call, this will change security settings for the file itself (and for all the file links). You should also keep in mind that calling CreateHardLink with a non-NULL lpSecurityAttributes argument most likely will fail if the user is not the owner of the file or a system administrator. It is not clear what reasons did Microsoft have for adding that argument — modifying file security the usual way, using the SetSecurityInfo function, would be a better practice.
Deleting A Hard Link
In order to delete a hard link, call the Windows API function DeleteFile, specifying the link path. The DeleteFile function removes the link and decreases the link count in the file’s MFT record. If the link count becomes zero, the system deletes the file, that is frees its MFT entry and disk space.
Note that there is no difference between the original file name and an additional hard link. Both are just pointers to the file’s MFT entry.
Enumerating Hard Links
Until Windows Vista the only documented way to find all the file’s links was scanning all the drive’s directories and opening every file. Calling GetFileInformationByHandle returned the unique file’s index in MFT. Files with the same index are hard links. Note also that there is no such thing as the ‘primary link’ – it is not possible to distinguish the ‘first’ file’s name without directly analyzing the file’s MFT entry.
Windows Vista introduced functions for locating all the file’s hard links – FindFirstFileNameW / FindFirstFileNameTransactedW and FindNextFileNameW (note that only UNICODE versions are available). The code example below prints all the hard links of a given file (which may be specified by any of its links).
The path returned by the functions FindFirstFileNameW and FindNextFileNameW does not contain a drive letter and always starts with the backslash character. The drive is assumed to be the same as the drive specified in the first FindFirstFileNameW argument (as it was noted earlier, hard link always points to the same drive).
NTFS Symbolic Links
Starting with Windows Vista, Microsoft added support for symbolic links to files and directories. Symbolic links are very similar to NTFS directory junctions, and unlike hard links, symbolic links can refer to non-existing objects and objects, residing on different (or even remote) drives.
Programming Considerations
There is only one API function for symbolic links – CreateSymbolicLink
The first argument is the path to the symbolic link object. The second one is an absolute or a relative path to the object the link points to. The last argument is a flag indicating if the target object is a file or if it is a directory. This flag is necessary because the target path argument may point to a non-existent object.
A symbolic link object may be deleted with the DeleteFile (or RemoveDirectory) function. It is not possible to copy a symbolic link – the copy operation will copy the referred file, not the link itself. You can find more information in the corresponding WinAPI article.
Microsoft wouldn’t be itself it it didn’t make a new cool feature pretty useless. CreateSymbolicLink function demands privilege elevation, i.e. the program must be Run as Administrator (this fact is however not mentioned in the Windows API documentation). Although this requirement has been removed in Windows 10, there still is a huge number of systems running older Windows versions.
Reparse Points and Directory Junctions
Reparse points provide another way of creating links. If a file or a directory has a reparse point attached, the system calls a file system filter, indicated by the reparse point tag. The filter may implement any method of accessing the actual data, including quite complicated ones. HSM (Hierarchical Storage Management) is a good example how useful reparse points can be.
Unfortunately, although we can link to directories using the reparse points mechanism (such links are called junctions), there is no way of linking to files short of writing a custom file system filter driver. Even if using reparse points is a natural way of implementing soft links, the gain is hardly worth the pain.
However reparse points are not all that useless for our purpose: junctions can supplement NTFS file-only hard links. Just keep in mind that they are, in fact, soft links, and if you move or delete the referred directory, the junction will point to nowhere. On the other hand, being a soft link, a junction is not limited to objects residing on the same drive; it can point to a directory on a different drive, or even to the drive itself (although a junction is not allowed to point to a mapped network object).
Programming Considerations
In order to improve readability, the code examples below don’t include any error processing. You should add some error checks if you want to use this code in your program. See the sources in the download section for an example of error handling.
Aside from a couple of overview articles, reparse points are very scantily documented, and the Platform SDK does not include the required definitions:
The header file WinNT.h included in the VC++ 6.0 distributive contains another definition (Microsoft removed it in the later versions of the Platform SDK):
We will use the former structure as defined in the Junctions example on the Systems Internals Web site.
Helper Functions
We will need a couple of helper functions. First one opens a directory and returns its handle:
The second helper function checks if the directory has an associated junction point:
Creating Directory Junction
The first step is creating a directory if it does not exists. If the directory exists, it must be empty — you cannot associate a reparse point with a non-empty directory.
The next step is obtaining the directory handle:
And the last step is the black magic:
Note that szTarget string must contain the path prefixed with the «non-parsed» prefix «\??\», and terminated with the backslash character, for example «\??\C:\Some Dir\».
You can save some effort by using the CreateJunction function you can find in the download section.
Deleting Directory Junction
If the directory is empty, you can use the RemoveDirectory function to remove both the directory and the associated junction point. Another way is to use DeviceIoControl, which does not require the directory to be empty and removes the junction only, leaving the directory and its content intact.
Querying Directory Junction
The following code returns the path the junction point is linked to:
Windows Shortcuts
A more advanced version of Windows symbolic link is shortcut. In addition to the basic link-to-file relationship a shortcut can also contain a description, an icon, and so on. In addition, shortcuts can point to non-file objects like printers.
A shortcut is actually a file, usually with the .lnk extension (any other extension can also be registered as a shortcut). Like any other file it can be copied, renamed, or deleted; file operations on a shortcut don’t affect the object being pointed to.
Programming Considerations
In order to improve readability, the code examples below don’t include any error processing. You should add some error checks if you want to use this code in your program. See the sources in the download section for an example of error handling.
Creating New Shortcut
In order to set up a Windows shortcut programmatically first create it using the IShellLink interface (don’t forget to call CoInitialize before calling any COM function).
If you want to create a shortcut for a non-file object, use the SetIDList function instead of SetPath. In this case you should use a pointer to the object’s ITEMIDLIST structure, or PIDL. PIDL is a more universal way of object addressing so you can use the SetIDList function for both file and non-file objects. You can obtain PIDLes for the standard shell objects by calling the SHGetFolderLocation or SHGetSpecialFolderLocation function. To convert a PIDL to the corresponding file path use the shell function SHGetPathFromIDList.
To set additional parameters like a description or an icon location use the appropriate IShellLink functions:
When the shortcut is set up completely, save it using the IPersistFile interface:
Please note that unlike IShellLink::SetPath, and like most COM/OLE functions, IPersistFile::Save requires a UNICODE path string.
As a final stroke, commit I/O by releasing the interface pointers, and the newly created shortcut is here!
Modifying Existing Shortcut
An existing shortcut can be modified using the same code; the only difference is that you should first read the shortcut using the IPersistFile::Load call. For example, a function for changing the path to the shortcut target would look as follows:
Deleting Shortcut
Simply delete the shortcut file using the standard DeleteFile API function.
Desktop? Where Is It?
You will probably want to place your shiny new shortcut on the desktop or in the Start menu. However the directories associated with the standard locations may vary for different Windows versions and localizations. If you want your code to work on different computers, you should never assume that the Desktop directory is C:\Document and Settings\All Users\Desktop or the Programs directory is C:\Program Files.
The Windows Shell API function SHGetSpecialFolderPath and the newer SHGetFolderPath retrieve the path of a special folder. However if a compatibility with older Windows versions is important, use the older function SHGetSpecialFolderLocation, which is supported by all Windows versions and does not require a redistributable.
Remember to free the PIDL when it is no more needed:
Notifying the Explorer
After you created or deleted a shortcut, you may need to use the SHChangeNotify function to notify the Windows Explorer about the change in the shortcut directory and to ensure the directory view is properly updated.
Downloads
All the content is provided on the «as is» basis and without any warranty, express or implied. You can use the supplied tools and examples for any commercial or non-commercial purpose without charge. You can copy and redistribute these tools and examples freely, provided that you distribute the original umodified archives.
Create Symbolic Links, Hard Links and Directory Junction Points in Windows with MKLINK
F or Unix-like or Linux system users, symbolic link is a common feature in use almost daily. Symbolic link (aka soft link) or symlink as it often shortened to, is a special type of file or file-system object that serves as a reference or points to another file, UNC or directory, known as target. In Windows systems such Windows Vista and Windows Server 2008, e.g. Windows 7, Windows 8, Windows 8.1, Windows 10, Windows Server 2008 R2, Windows Server 2012, Windows Server 2012 R2 and Windows Server 2016, symlinks feature has been added to NTFS filesystem and can be created by using MKLINK command.
In previous Windows operating system such as Windows XP, the closer thing to symbolic links is NTFS junction point, or worse, Windows shell shortcut (.lnk) file.
Symlink in Windows, unlike .lnk shortcut in desktop or Windows Explorer, allow user to access files within the symbolic link created itself via File Explorer, the console and etc. And symbolic link also differ from NTFS junction point which can only link to folders and volumes, in which symlinks can point to a file, a UNC, a folder or a volume, as well as able to span file systems.
Symbolic link is useful when you have a lot of folders and files are scattered all over the directory tree, and you need to manage them from a single location. Another scenario is that you have a deep nested file that you want to access quickly instead of traverse through one branch by one branch. And furthermore, for programmer, symlink provides a static file path that can be point to a ever changing object without affecting the functionality of the program. In all these situation, symbolic links can be created at a convenient location which point to the ‘real’ objects.
As mentioned, to create a symbolic link, use MKLINK command line tool. MKLINK can be used to create a hard link or directory junction (junction point) too. Hard link is essentially giving another name or label to the objects, while NTFS directory junction point is used to redirect the whole folder to another folder as if it’s the original folder itself. Junction point is used extensively in Windows to provide support for old directory structures for user profiles (i.e Documents and Settings) to point to the new user folders located inside Users directory.
Syntax and Options of MKLINK
MKLINK [[/D] | [/H] | [/J]] Link Target
/D – Creates a directory symbolic link. Default to file symbolic link.
/H – Creates a hard link instead of a symbolic link.
/J – Creates a Directory Junction.
Link – Specifies the new symbolic link name.
Target – Specifies the path (relative or absolute) that the new link refers to.
Examples and Usages of MKLINK
Note: Only Administrators can use MKLINK to create symbolic links unless override by using secpol.msc, so you need to run Command Prompt with elevated privileges, or else you will get “You do not have sufficient privilege to perform this operation.” error.
To create symbolic link called foo to reference to c:\Windows\System32\notepad.exe:
You will see the following result:
If you type dir in commnd prompt, you will see the following listing:
To create symbolic link to a folder, simply use /D switch, or /J for junction point (directory junction is not available for remote network location):
Results of dir command:
MKLINK cannot be used to delete symbolic link. To remove a symbolic link, simply delete them as if you’re removing a normal file. For example, to delete the foo symbolic link created above, enter the following command:
To remove the bar symbolic link to a folder created above, use the following command: