Create Symbolic Links on Windows with .NET

Create Symbolic Links on Windows with .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.

using System;
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;

class Program
{
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool CreateSymbolicLink(
        string lpSymlinkFileName, string lpTargetFileName, SymbolicLink dwFlags);

    enum SymbolicLink
    {
        File = 0,
        Directory = 1
    }

    static void Main(string[] args)
    {
        string linkPath = @"C:\link";
        string targetPath = @"C:\target";

        bool linkCreated = CreateSymbolicLink(linkPath, targetPath, SymbolicLink.Directory);

        if (linkCreated)
        {
            Console.WriteLine("CreateSymbolicLink succeeded.");
        }
        else
        {
            int errorCode = Marshal.GetLastWin32Error();
            Console.WriteLine("CreateSymbolicLink failed with error code: " + errorCode);
        }
    }
}

To map an error code (int) to a useful message, you have to look into the Windows Error Codes table. Windows System Error Codes