C#在Linux下获取文件夹信息(所在磁盘总大小,使用空间,已用空间,使用率)
1.第一种使用shell命令实现:
1 private DiskInfo LinuxGetFolderDiskInfo(string path) 2 { 3 DiskInfo disk = new DiskInfo(); 4 if (string.IsNullOrEmpty(path)) 5 { 6 return disk; 7 } 8 if (!path.StartsWith("/")) 9 { 10 path = "/" + path; 11 } 12 13 string shellPathLine = string.Format("cd {0}", path); 14 string printLine = " awk '{print $2,$3,$4,$5}'"; 15 string shellLine = string.Format("df -k {0} |", path) + printLine; 16 logger.Debug(string.Format("执行命令:{0}", shellLine)); 17 18 Process p = new Process(); 19 p.StartInfo.FileName = "sh"; 20 p.StartInfo.UseShellExecute = false; 21 p.StartInfo.RedirectStandardInput = true; 22 p.StartInfo.RedirectStandardOutput = true; 23 p.StartInfo.RedirectStandardError = true; 24 p.StartInfo.CreateNoWindow = true; 25 p.Start(); 26 p.StandardInput.WriteLine(shellPathLine); 27 p.StandardInput.WriteLine(shellLine); 28 p.StandardInput.WriteLine("exit"); 29 30 string strResult = p.StandardOutput.ReadToEnd(); 31 logger.Debug(string.Format("输出结果:{0}", strResult)); 32 string[] arr = strResult.Split('\n'); 33 if (arr.Length==0) 34 { 35 return disk; 36 } 37 string[] resultArray = arr[1].TrimStart().TrimEnd().Split(' '); 38 if (resultArray==null || resultArray.Length == 0) 39 { 40 return disk; 41 } 42 43 disk.TotalSize = Convert.ToInt32(resultArray[0]); 44 disk.UsedSize = Convert.ToInt32(resultArray[1]); 45 disk.AvailableSize = Convert.ToInt32(resultArray[2]); 46 disk.Use = resultArray[3]; 47 logger.Debug(string.Format("Linux获取目录:{0},总大小:{1},已用:{2},未用:{3},使用率:{4}", path, disk.TotalSize, disk.UsedSize, disk.AvailableSize, disk.Use)); 48 49 return disk; 50 }
2.第二种使用statvfs()函数实现:(需要下载Mono.Posix.dll,引用using Mono.Unix.Native;)
1 public DiskInfo LinuxGetFolderDiskInfo(string path) 2 { 3 DiskInfo disk = new DiskInfo(); 4 try 5 { 6 if (string.IsNullOrEmpty(path)) 7 { 8 return disk; 9 } 10 if (!path.StartsWith("/")) 11 { 12 path = "/" + path; 13 } 14 15 Statvfs stavfs; 16 Syscall.statvfs(path, out stavfs); 17 disk.TotalSize = (long)(stavfs.f_blocks * stavfs.f_bsize); 18 disk.AvailableSize = (long)(stavfs.f_bavail * stavfs.f_bsize); 19 disk.UsedSize = (long)(stavfs.f_bfree * stavfs.f_bsize); 20 21 logger.Debug(string.Format("Linux获取目录:{0},总大小:{1},已用:{2},未用:{3}", path, disk.TotalSize, disk.UsedSize, disk.AvailableSize)); 22 return disk; 23 } 24 catch (Exception ex) 25 { 26 logger.Error(ex); 27 return disk; 28 } 29 }
1 public class DiskInfo 2 { 3 public long TotalSize { get; set; } 4 5 public long UsedSize { get; set; } 6 7 public long AvailableSize { get; set; } 8 9 public string Use { get; set; } 10 }