What the C# equivalent of “mklink /J”?

后端 未结 3 1834
梦毁少年i
梦毁少年i 2020-12-24 01:39

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

mklink /J  

How to do the sam

3条回答
  •  生来不讨喜
    2020-12-24 02:04

    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.

提交回复
热议问题