在Linux上的C#中查找目录的可用空间

时间:2014-11-12 14:07:37

标签: c# linux mono cross-platform diskspace

我需要可以在Visual Studio和Visual Studio下编译的代码。单声道,&在Linux或Windows上运行。

我需要返回可用空间,只给出目录的路径。

在Windows上,我会按照以下方式做点什么 -

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

然而在Linux上,这似乎抛出了一个Argument Exception。 file.Directory.Root.FullName返回'/'。 DriveInfo抛出“驱动器名称不存在”的参数异常

有什么想法吗?

由于

1 个答案:

答案 0 :(得分:0)

您可以简单地使用linux df命令。这将为您返回计算机上所有可用磁盘的摘要。

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%| /

相关问题