如何让VB.NET程序自动以GB/TB显示磁盘空间并保留两位小数?
VB.NET自动选择GB/TB单位显示磁盘空间
我需要修改一段VB.NET控制台程序,让它根据磁盘的实际大小自动选择以GB或TB为单位显示可用空间和总容量,同时将结果保留两位小数(例如2.14 TB)。目前我已经掌握了字节转GB(TotalFreeSpace / 2^30)和TB(TotalFreeSpace / 2^40)的计算公式,但不知道如何实现单位的自动切换。
原代码
Class Test Public Shared Sub Main() Dim allDrives() As DriveInfo = DriveInfo.GetDrives() Dim d As DriveInfo For Each d In allDrives Console.WriteLine("Drive {0}", d.Name) Console.WriteLine(" Drive type: {0}", d.DriveType) If d.IsReady = True Then Console.WriteLine(" Volume label: {0}", d.VolumeLabel) Console.WriteLine(" File system: {0}", d.DriveFormat) Console.WriteLine( " Total available space: {0, 15} bytes", d.TotalFreeSpace) Console.WriteLine( " Total size of drive: {0, 15} bytes ", d.TotalSize) End If Next End Sub End Class
解决方案代码
通过编写一个辅助函数来处理单位转换和自动匹配,实现需求:
Class Test Public Shared Sub Main() Dim allDrives() As DriveInfo = DriveInfo.GetDrives() Dim d As DriveInfo For Each d In allDrives Console.WriteLine("Drive {0}", d.Name) Console.WriteLine(" Drive type: {0}", d.DriveType) If d.IsReady = True Then Console.WriteLine(" Volume label: {0}", d.VolumeLabel) Console.WriteLine(" File system: {0}", d.DriveFormat) Console.WriteLine(" Total available space: {0}", FormatSpace(d.TotalFreeSpace)) Console.WriteLine(" Total size of drive: {0}", FormatSpace(d.TotalSize)) End If Next End Sub ' 辅助函数:将字节转换为合适的GB/TB单位,保留两位小数 Private Shared Function FormatSpace(bytes As Long) As String Const GB As Double = 1024 ^ 3 ' 等价于2^30 Const TB As Double = 1024 ^ 4 ' 等价于2^40 If bytes >= TB Then Return String.Format("{0:0.00} TB", bytes / TB) ElseIf bytes >= GB Then Return String.Format("{0:0.00} GB", bytes / GB) Else ' 可选:若需支持更小单位(如MB)可在此扩展,当前默认保留字节显示 Return String.Format("{0} bytes", bytes) End If End Function End Class
代码说明
- 新增
FormatSpace辅助函数,根据传入的字节数自动判断显示单位:- 当字节数≥1TB时,转换为TB单位并保留两位小数
- 当字节数≥1GB但不足1TB时,转换为GB单位并保留两位小数
- 对于小于1GB的磁盘,默认保留字节显示(可按需扩展为MB等单位)
- 主程序中直接调用该函数,替代原有的字节输出逻辑,实现自动匹配单位的效果
内容的提问来源于stack exchange,提问作者dpresnell90
相关产品推荐
相关产品推荐

