Samuel Rossille Samuel Rossille - 1 month ago 7
C# Question

What the C# equivalent of "mklink /J"?

I know how to create a symbolic link in windows in a .bat script:

mklink /J <LinkPath> <OriginalResourcePath>


How to do the same thing in C# ?

I've not been happy with the googling, because i'm a beginner in C# and I probably don't use the right terms. Anybody can indicate the API to use please ?

Answer

Here's a code example:

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

        enum SymbolicLink
        {
            File = 0,
            Directory = 1
        }

        static void Main(string[] args)
        {
            string symbolicLink = @"c:\bar.txt";
            string fileName = @"c:\temp\foo.txt";

            using (var writer = File.CreateText(fileName))
            {
                writer.WriteLine("Hello World");
            }

            CreateSymbolicLink(symbolicLink, fileName, SymbolicLink.File);
        }
    }
}

This will create a symbolic link file called bar.txt on the C:-drive which links to the foo.txt text file stored in the C:\temp directory.