Finding free space for a directory in C # on Linux

I need code that can compile under Visual Studio and Mono and run on Linux or Windows.

I need to return the free space available only for the directory path.

In the windows I did something line by line -

var file  = new FileInfo(path);
var drive = new DriveInfo(file.Directory.Root.FullName);
return drive.AvailableFreeSpace;

However, on Linux, this seems to throw an Argument exception. file.Directory.Root.FullName returns '/'. DriveInfo throws an exception to the argument "Drive name does not exist"

Any ideas?

thank

+4
source share
1 answer

You can simply use the linux df command. This will return you a summary of all available disks on your computer.

public static class ServersManager
{      
        public static string GetDiskSpace()
        {
            return string.Join(" ", "df").Bash();
        }

        private static string Bash(this string cmd)
        {
            var escapedArgs = cmd.Replace("\"", "\\\"");

            var process = new Process()
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = "/bin/bash",
                    Arguments = $"-c \"{escapedArgs}\"",
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true,
                }
            };
            process.Start();
            string result = process.StandardOutput.ReadToEnd();
            process.WaitForExit();
            return result;
        }
}

GetDiskSpace :

| 1K- | | | % |

/dev/sda4 | 497240864 | 31182380 | 466058484 | 7% |/

0

All Articles