
This article was written in 2023. Versions, tools and recommendations may have changed since then. Newer posts are collected under .NET.
Symbolic Links (often abbreviated as symlinks) are a type of file or folder shortcut in Windows that reference another file or folder in the file system, rather than copying its contents. Unlike a normal shortcut, a symlink acts as if it were the original file or folder, so any changes to the symlink will affect the original file and vice versa.
Symlinks can be used to create shortcuts to files or folders that are located on another drive, in another location on the same drive or even on a network location. They can also be used to redirect files or folders to a new location or to create multiple references to the same file or folder.
.NET has no built-in API to create symbolic links on Windows. However, it is possible to create symbolic links on Windows with .NET by using the CreateSymbolicLink method of the Win32 class in the Microsoft.Win32.SafeHandles namespace.
1using System;
2using Microsoft.Win32.SafeHandles;
3using System.Runtime.InteropServices;
4
5class Program
6{
7 [DllImport("kernel32.dll", SetLastError = true)]
8 static extern bool CreateSymbolicLink(
9 string lpSymlinkFileName, string lpTargetFileName, SymbolicLink dwFlags);
10
11 enum SymbolicLink
12 {
13 File = 0,
14 Directory = 1
15 }
16
17 static void Main(string[] args)
18 {
19 string linkPath = @"C:\link";
20 string targetPath = @"C:\target";
21
22 bool linkCreated = CreateSymbolicLink(linkPath, targetPath, SymbolicLink.Directory);
23
24 if (linkCreated)
25 {
26 Console.WriteLine("CreateSymbolicLink succeeded.");
27 }
28 else
29 {
30 int errorCode = Marshal.GetLastWin32Error();
31 Console.WriteLine("CreateSymbolicLink failed with error code: " + errorCode);
32 }
33 }
34}To map an error code (int) to a useful message, you have to look into the Windows Error Codes table. Windows System Error Codes
Related articles

- 16 min read
Production Rate Limiting in ASP.NET Core
Most ASP.NET Core rate-limiting examples stop after registering a fixed window. That is enough to demonstrate the middleware, but it is not …

- 11 min read
The Big Decimal Bugfix with .NET 11
For more than two decades, (decimal)1.23 returned 1.23m. It looked correct, it passed every test and it was a polite lie.

- 10 min read
Distroless, Chiseled or Alpine: Choosing a .NET Base Image
Distroless, Chiseled and Alpine are often compared as three equivalent Linux distributions. They are not. Alpine is a distribution built …
Let's Work Together
Looking for an experienced Platform Architect or Engineer for your next project? Whether it's cloud migration, platform modernization or building new solutions from scratch - I'm here to help you succeed.
