ASP Drive

Drive 对象的属性、遍历驱动器、可用空间查询。

Intermediate
Key PointsDrive 对象描述一个磁盘分区:盘符、类型、文件系统、总容量与剩余空间。

属性

PropertyExample
DriveLetterC
PathC:
DriveType0 未知 / 1 可移动 / 2 固定 / 3 网络 / 4 CD / 5 RAM
FileSystemNTFS、FAT32
TotalSize字节数
FreeSpace字节数
AvailableSpace对当前用户可用
IsReady光驱无盘时为 False
SerialNumber卷序列号
VolumeName系统

取一个驱动器

ASP
<%
    Dim fso, d
    Set fso = Server.CreateObject("Scripting.FileSystemObject")
    Set d = fso.GetDrive("C")

    Response.Write "盘符:" & d.DriveLetter & "<br>"
    Response.Write "类型:" & d.DriveType & "<br>"
    Response.Write "文件系统:" & d.FileSystem & "<br>"
    Response.Write "总容量:" & FormatNumber(d.TotalSize / 1024 / 1024 / 1024, 1) & " GB<br>"
    Response.Write "剩余:" & FormatNumber(d.FreeSpace / 1024 / 1024 / 1024, 1) & " GB<br>"
    Response.Write "卷标:" & d.VolumeName

    Set d = Nothing
    Set fso = Nothing
%>
Output
盘符:C
类型:2
文件系统:NTFS
总容量:476.9 GB
剩余:128.4 GB
卷标:系统

遍历所有驱动器

ASP
<%
    Dim d, t
    For Each d In fso.Drives
        t = ""
        Select Case d.DriveType
            Case 1 : t = "可移动"
            Case 2 : t = "本地磁盘"
            Case 3 : t = "网络驱动器"
            Case 4 : t = "光驱"
            Case 5 : t = "RAM 盘"
            Case Else : t = "未知"
        End Select

        Response.Write d.DriveLetter & ": " & t
        If d.IsReady Then
            Response.Write " — 剩余 " & FormatNumber(d.FreeSpace / 1073741824, 1) & " GB"
        End If
        Response.Write "<br>"
    Next
%>
Output
C: 本地磁盘 — 剩余 128.4 GB
D: 本地磁盘 — 剩余 512.0 GB
E: 光驱

Check IsReady before touching anything. An empty optical drive or a disconnected network share throws on FreeSpace and aborts the loop.

磁盘空间监控

ASP
<%
    Dim freeGB
    freeGB = fso.GetDrive("C").FreeSpace / 1073741824

    If freeGB < 5 Then
        ' 写告警日志
        Set ts = fso.OpenTextFile(Server.MapPath("/logs/disk.log"), 8, True)
        ts.WriteLine Now() & " 磁盘剩余 " & FormatNumber(freeGB, 2) & " GB"
        ts.Close
    End If
%>
Exposing disk details is risky: free space, volume labels and filesystem type all help an attacker profile the host. Such pages belong behind admin authentication.

单位换算

ASP
<%
    Function Human(bytes)
        Dim units, i
        units = Array("B", "KB", "MB", "GB", "TB")
        i = 0
        Do While bytes >= 1024 And i < UBound(units)
            bytes = bytes / 1024
            i = i + 1
        Loop
        Human = FormatNumber(bytes, 1) & " " & units(i)
    End Function

    Response.Write Human(184320)
%>
Output
180.0 KB

FormatNumber(x, 1) keeps one decimal. Note it follows Session.LCID for separators: 2052 uses ., while some European locales use , — worth remembering when the value feeds a data interface.

Friends & Partners