Creating windows symbolic link

How to Create Symbolic Links (Symlink) in Windows 10

Symlinks or Symbolic Links is one of the lesser known, yet useful, features in Windows. You can think of symbolic links as the shortcuts you create in Windows. However, symbolic links are much more powerful and helpful than regular shortcuts. Let’s discuss what symbolic links are and how you can easily create them in Windows 10.

When you create a shortcut for a file or folder, all you are doing is pointing it to that specific file or folder, nothing more. Symbolic links are much more than a simple shortcut. They act as a virtual file or folder that links to the actual file or folder.

When you create a symlink for a file, it appears as if it is the actual file when in reality it is redirecting you toward the real file in the background. Besides files, you can also create symlinks for folders. Simply put, a symlink is nothing more than a build of the text string which lets the operating system know that it is just a path for another file or folder.

For instance, most cloud service apps you install will only sync files and folders located in their own folder. But there will be times when you might have a folder in some other drive you want to sync with the cloud storage service.

However, you don’t want to move the folder from its actual location or don’t want to create a copy of the folder. In those situations you can simply create a symlink in the cloud service folder so that you can sync the contents of the target folder without actually moving or copying the real folder.

Since a symlink is just a virtual folder that just acts as a path to the real folder, you don’t have to worry about the symlink consuming your disk space.

If you don’t want to faff around in the Command Prompt and are prepared to faff around a little bit by installing a tool that lets you create symlinks to an existing file or directory using the right-click context menu, then try the following. Link Shell Extension is a tool that lets you create hardlinks and symbolic links by right-clicking whatever folder you want to create a link to.

There are a few hoops with the installation. You’ll get a warning that it can’t be downloaded securely, and Windows Defender may warn you that it’s “unsigned.”

We can assure you that the tool is safe. Go ahead and install it. During installation, explorer.exe will restart, so make sure you have important stuff backed up.

Once LSE is installed, right-click the target file or folder you want to create a symlink to, then click “Pick Link Source.”

Next, go to the folder where you want the symlink to appear, right-click it, then select “Drop As -> Symbolic Link.”

Читайте также:  После обновления mac os пропал звук

Note: though I’m showing this in Windows 10, the commands shown here are applicable to Windows Vista and up.

Creating symlinks in Windows is pretty easy with the mklink command. To start, press Win + X , then select the option “Command Prompt (Admin)” to open the Command Prompt with admin rights.

Once the command prompt has been opened, use the below command format to create a symlink for a file.

In my case, I want to create a symlink in the E drive for a text file located on the F drive, so the command looks something like this:

The first path you see in the above command is where you will create your symlink. This path is called a “Link.” The second path belongs to the actual file on your disk and is called “Target.”

Once the symlink has been created, this is how it looks in the File Explorer. Though the icon looks like a regular shortcut, it is a symlink.

Along with individual files, you can create symlinks for entire directories. To do that, use the below command. The switch /D allows you to do this.

As soon as you execute the command, the symlink will be created for the target directory. You can use it to access all the files and folders inside the real folder. If you ever want to, you can delete the symbolic link like any other file or folder. Just select the symlink, press the delete key on your keyboard, and you are good to go.

And you’re done! If you want to do more under-the-hood tweaking in Windows 10, see our list of the best registry hacks. Also, check out our guide on how to get Mac-style hot corners in Windows 10.

CreateSymbolicLinkA function (winbase.h)

Creates a symbolic link.

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

Syntax

Parameters

The symbolic link to be created.

This parameter may include the path. 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.

The name of the target for the symbolic link to be created.

If lpTargetFileName has a device name associated with it, the link is treated as an absolute link; otherwise, the link is treated as a relative link.

This parameter may include the path. 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.

Indicates whether the link target, lpTargetFileName, is a directory.

Value Meaning
0x0 The link target is a file.
SYMBOLIC_LINK_FLAG_DIRECTORY 0x1 The link target is a directory.
SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE 0x2 Specify this flag to allow creation of symbolic links when the process is not elevated. Developer Mode must first be enabled on the machine before this option will function.

Return value

If the function succeeds, the return value is nonzero.

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

Remarks

Symbolic links can either be absolute or relative links. Absolute links are links that specify each portion of the path name; relative links are determined relative to where relative–link specifiers are in a specified path. Relative links are specified using the following conventions:

  • Dot (. and ..) conventions—for example, «..\» resolves the path relative to the parent directory.
  • Names with no slashes (\\)—for example, «tmp» resolves the path relative to the current directory.
  • Root relative—for example, «\Windows\System32» resolves to «current drive:\Windows\System32″.
  • Current working directory–relative—for example, if the current working directory is C:\Windows\System32, «C:File.txt» resolves to «C:\Windows\System32\File.txt».

In WindowsВ 8 and Windows ServerВ 2012, this function is supported by the following technologies.

Technology Supported
Server Message Block (SMB) 3.0 protocol Yes
SMB 3.0 Transparent Failover (TFO) Yes
SMB 3.0 with Scale-out File Shares (SO) No
Cluster Shared Volume File System (CsvFS) No
Resilient File System (ReFS) Yes

В

CsvFs does not support soft link or any other reparse points.

The winbase.h header defines CreateSymbolicLink as an alias which automatically selects the ANSI or Unicode version of this function based on the definition of the UNICODE preprocessor constant. Mixing usage of the encoding-neutral alias with code that not encoding-neutral can lead to mismatches that result in compilation or runtime errors. For more information, see Conventions for Function Prototypes.

Creating Symbolic Links

The function CreateSymbolicLink allows you to create symbolic links using either an absolute or relative path.

Symbolic links can either be absolute or relative links. Absolute links are links that specify each portion of the path name; relative links are determined relative to where relative–link specifiers are in a specified path. Relative links are specified using the following conventions:

Dot (. and ..) conventions—for example, «..\» resolves the path relative to the parent directory.

Names with no slashes ()—for example, «tmp» resolves the path relative to the current directory.

Root relative—for example, «\Windows\System32» resolves to the «current drive:\Windows\System32″. directory

Current working directory-relative—for example, if the current working directory is «C:\Windows\System32», «C:File.txt» resolves to «C:\Windows\System32\File.txt».

Note  If you specify a current working directory–relative link, it is created as an absolute link, due to the way the current working directory is processed based on the user and the thread.

A symbolic link can also contain both junction points and mounted folders as a part of the path name.

Symbolic links can point directly to a remote file or directory using the UNC path.

Relative symbolic links are restricted to a single volume.

In this example, the original path contains a component, ‘x‘, which is an absolute symbolic link. When ‘x‘ is encountered, the fragment of the original path up to and including ‘x‘ is completely replaced by the path that is pointed to by ‘x‘. The remainder of the path after ‘x‘ is appended to this new path. This now becomes the modified path.

Link: «absLink» maps to «\\machineB\share»

Modified Path: «\\machineB\share\gamma\file»

In this example, the original path contains a component ‘x‘, which is a relative symbolic link. When ‘x‘ is encountered, ‘x‘ is completely replaced by the new fragment pointed to by ‘x‘. The remainder of the path after ‘x‘, is appended to the new path. Any dots (..) in this new path replace components that appear before the dots (..). Each set of dots replace the component preceding. If the number of dots (..) exceed the number of components, an error is returned. Otherwise, when all component replacement has finished, the final, modified path remains.

Link: «link» maps to «..\..\theta»

Modified Path: «C:\alpha\beta\..\..\theta\gamma\file»

Как создать символьную ссылку в Windows 10, 8.1, 8, 7

Товарищи, добрый день. Хотя эта тема и не самая популярная, но она мне очень много раз выручала, поэтому я не могу о ней не написать. Итак, что значит термин «символьная ссылка» я возьму из энциклопедии Wikipedia:

Символьная ссылка (также симлинк от англ. Symbolic link, символическая ссылка) — специальный файл в файловой системе, для которого не формируются никакие данные, кроме одной текстовой строки с указателем. Эта строка трактуется как путь к файлу, который должен быть открыт при попытке обратиться к данной ссылке (файлу). Символьная ссылка занимает ровно столько места в файловой системе, сколько требуется для записи её содержимого (нормальный файл занимает как минимум один блок раздела).

По своей сути же, симлинк — это ярлык, который позволяет системе думать, что это не ярлык, а настоящий файл (или папка). К примеру, частое применение символьной ссылок для папок — это установка игры на SSD, с последующем переносом файлов графики на жесткий диск, с целью экономия места на SSD и создание символьной ссылки до исходного места. Игра будет думать, что все файлы находятся в исходной папке. Так же символьные ссылки можно применять когда используются одинаковые файлы в нескольких каталогах, чтобы не вносить правки во все файлы, можно создать с одного файла символьные ссылки и вносить изменения один раз.

Создать символьную ссылку очень просто и сейчас я вам это докажу. Открываем командную строку, нажимаем Win+R, вводим cmd и жмём ОК. Хотя если вы собираетесь работать с системными файлами, может понадобиться командная строка с правами администратора.

Дальше нам нужно ввести команду для создания символьной ссылки, выглядит она следующем образом:

где /j — атрибут создания соединения для каталога. Если вы создаете ссылку на файл, атрибут ставить не надо.

К примеру, если я хочу создать символьную ссылку на папку mklink на локальном диске E, как папку mk на диске С, мне нужно ввести следующую команду (и да, символьная ссылка может называться не так, как исходный файл (папка):

В результате мы получим вот это.

Если же мы хотим создать символьную ссылку на файл, например на файл 1.txt, хранящийся в корне диска E. для использования в виде файла 2.txt. скажем в папке mslink на диске C, команда будет выглядеть вот так:

А на выходе получим вот это.

Резюмируя скажу, что знание возможностей данной функции, открывает большие возможности. С помощью неё я выходил из нескольких ситуаций, когда не хватало свободного пространства, на моем старом SSD, позволяя быстро перенести игру из папки origin на другой диск. Но вариантов использования её гораздо больше, к примеру перенос кэша браузеров, о котором мы поговорим в одной из будущих статей.

Вроде всё. Надеюсь эта статья оказалась вам полезной, обязательно нажмите одну из кнопок ниже, чтобы рассказать о ней друзьям. Также подпишитесь на обновления сайта, введя свой e-mail в поле справа или подписавшись на группу во Вконтакте и канал YouTube.
Спасибо за внимание

Читайте также:  Windows speech recognition russian
Оцените статью