C#基础 DriveInfo GetDrives 获取电脑上的所有逻辑驱动器的名称,可用空间,总空间

    xiaoxiao2022-07-07  220

    .NET Framework : 4.7.2       IDE : Visual Studio Community 2019        OS : Windows 10 x64    typesetting : Markdown        blog : blog.csdn.net/yushaopu       github : github.com/GratefulHeartCoder

    code

    using System; using System.Globalization; using System.IO; namespace ConsoleApp { class Program { /// <summary> /// 因为C#提供的文件的大小是以B为单位的,所以显示文件大小的时候会出现一大串数字很不方便 /// 所以,该函数为了方便地显示文件大小而出现 /// 函数说明, /// 如果文件大小是0-1024B 以内的 显示以B为单位 /// 如果文件大小是1KB-1024KB之间的 显示以KB为单位 /// 如果文件大小是1M-1024M之间的 显示以M为单位 /// 如果文件大小是1024M以上的 显示以GB为单位 /// </summary> /// <param name="lengthOfDocument"> 文件的大小 单位:B 类型:long</param> /// <returns></returns> static string GetLength(long lengthOfDocument) { var nfi = new NumberFormatInfo(); nfi.NumberDecimalDigits = 2; if (lengthOfDocument < 1024) return string.Format(lengthOfDocument.ToString("N", nfi) + 'B'); else if (lengthOfDocument > 1024 && lengthOfDocument <= Math.Pow(1024, 2)) return string.Format((lengthOfDocument / 1024.0).ToString("N", nfi) + "KB"); else if (lengthOfDocument > Math.Pow(1024, 2) && lengthOfDocument <= Math.Pow(1024, 3)) return string.Format((lengthOfDocument / 1024.0 / 1024.0).ToString("N", nfi) + "M"); else return string.Format((lengthOfDocument / 1024.0 / 1024.0 / 1024.0).ToString("N", nfi) + "G"); } static void Main(string[] args) { var allDrives = DriveInfo.GetDrives(); foreach (var aDrive in allDrives) { if (aDrive.IsReady) { Console.Write("名字:{0,-10}", aDrive.Name); Console.Write(" 可用空间:{0,-20}", GetLength(aDrive.TotalFreeSpace)); Console.Write(" 总空间:{0,-20}", GetLength(aDrive.TotalSize)); // 空一行 Console.WriteLine(); } } // 其实这里还可以用异步的方法来处理。 foreach (var aDrive in allDrives) { if (aDrive.IsReady == false) { Console.Write("名字:{0,-10}", aDrive.Name); Console.Write("类型:" + aDrive.DriveType); Console.WriteLine(" 它不能获取可用空间"); } } Console.ReadKey(); } } }

    result

    名字:C:\ 可用空间:139.20G 总空间:201.49G 名字:D:\ 可用空间:157.82G 总空间:223.57G 名字:E:\ 可用空间:260.07G 总空间:263.67G 名字:F:\ 可用空间:636.13G 总空间:736.20G 名字:H:\ 类型:CDRom 它不能获取可用空间

    resource

    [文档] docs.microsoft.com/zh-cn/dotnet/csharp[规范] github.com/dotnet/docs/tree/master/docs/standard/design-guidelines[源码] referencesource.microsoft.com [平台] www.csdn.net[ IDE ] visualstudio.microsoft.com/zh-hans[.NET Core] dotnet.github.io


    感恩曾经帮助过 心少朴 的人。 C#优秀,值得学习。.NET Core具有跨平台的能力,值得关注。 Console,WinForm,WPF,ASP.NET,Azure WebJob,WCF,Unity3d,UWP可以适当地了解。 注:此文是自学笔记所生,质量中下等,故要三思而后行。新手到此,不可照搬,应先研究其理象数,待能变通之时,自然跳出深坑。

    最新回复(0)