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

Issue

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 ?

Solution

Warning: The question is not clear as it refers to symbolic links but at the same time refers to the /J switch that is used to create a junction. This answer refers to "how to create a symbolic link in c#" (without the /J). Instead, For creating junctions, please refer to In .NET, how do I Create a Junction in NTFS, as opposed to a Symlink?.

This is how symbolic links can be created:

using System.Runtime.InteropServices;
using System.IO;

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.

Answered By – Christophe Geers

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published