File permissions on Linux/Unix with .NET Core

Viewed 21555

I am trying to learn how to set file permissions on Linux/Unix with .NET Core. I already found a question on here that points me in the direction of System.IO.FileSystem, but I can't seem to find any documentation on how to use it.

In a nutshell, I'd like to chmod a file 644 from a .NET Core application that only runs on Linux, but am at a loss on how to proceed.

4 Answers

Similar approach as the one suggested by @kspearrin, but using CliWrap for simplicity:

public static async ValueTask SetPermissionsAsync(string filePath, string permissions) =>
    await Cli.Wrap("/bin/bash")
        .WithArguments(new[] {"-c", $"chmod {permissions} {filePath}"})
        .ExecuteAsync();

Handles escaping, errors, etc. automatically.

Here is a simple chmod function that you can use in c# with no depencencies.

// Returns true if success and false otherwise
// permissions can be an int or a string. For example it can also be +x, -x etc..
bool Chmod(string filePath, string permissions = "700", bool recursive = false)
{
        string cmd;
        if (recursive)
            cmd = $"chmod -R {permissions} {filePath}";
        else
            cmd = $"chmod {permissions} {filePath}";

        try
        {
            using (Process proc = Process.Start("/bin/bash", $"-c \"{cmd}\""))
            {
                proc.WaitForExit();
                return proc.ExitCode == 0;
            }
        }
        catch
        {
            return false;
        }
}
Related