C
C#2y ago
robb06

❔ Hardlink in Linux .NET 6.0

Dose anyone have a solution or guide to tell me how to essentially ln from within a .NET 6.0 console program ? If I have to spawn ln I will but I'd rather achieve it without that if possible.
4 Replies
Klarth
Klarth2y ago
You'll need to p/invoke something native. Possibly libc's link. You can run through an example like https://github.com/ProfessionalCSharp/ProfessionalCSharp2021/blob/main/5_More/PInvoke/PInvokeSampleLib/Linux/LinuxNativeMethods.cs Since you're on .NET 6, you won't be able to use [LibraryImport]. You'll need to use the older [DllImport]. There are probably other examples on GitHub if you search DllImport libc link and filter to C# if necessary. (Also verify that the docs state it creates a hard link and not a symbolic link.)
mtreit
mtreit2y ago
using System.Runtime.InteropServices;

int result = link("a.txt", "link.txt");
Console.WriteLine(result);

[DllImport("libc")]
static extern int link(string oldpath, string newpath);
using System.Runtime.InteropServices;

int result = link("a.txt", "link.txt");
Console.WriteLine(result);

[DllImport("libc")]
static extern int link(string oldpath, string newpath);
This seems to work...
robb06
robb06OP2y ago
oh nice, thank you. I will look at that now 🙂
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server