Finding available space for a directory in C# on Linux

2.9k views Asked by At

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

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

On windows I'd do something along the lines of -

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 Argument Exception of 'The drive name does not exist'

Any ideas?

Thanks

1

There are 1 answers

0
Roi Krakovski On

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;
        }
}

The function GetDiskSpace returns a table of the following form:

Filesystem | 1K-blocks | Used | Available | Use% | Mounted on

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