Check file properties using WMI

Using the Win32_Directory WMI class we can check various file properties.

Specifically, you can check

  • the date a file was last accessed.
  • the date a file was created.
  • the file extension and name (without having to parse Strings).
  • whether a file is writeable.

I know you can do most or all of these things with Windows APIs, but I find this method easier. First we need to access WMI. We do so using the following function:

Function GetAnotherWMIService() As Object
Dim strComputer As String

  strComputer = "."

  Set GetAnotherWMIService = GetObject _
                             ("winmgmts:" & "!\\" & strComputer & "\root\cimv2")

End Function

Since this WMI class returns information about a single file, the best thing we can do is come up with a function that takes a single filename as an argument and returns its properties as an array. Then we can iterate the array to read the information.

The GetFileInfo Function

The following function takes one argument (the filename to be examined) and returns a String array of properties about that file. Any backslashes found in the filepath must be escaped, i.e. "C:\MyFile.txt" must be passed as "C:\\MyFile.txt".

Function GetFileInfo(fileName As String) As String()
' http://msdn.microsoft.com/en-us/library/aa394130(VS.85).aspx
Dim objWMI As Object
Dim colFiles As Object
Dim objFile As Object
Dim vtemp() As String

Const NUMBER_OF_PROPERTIES As Long = 11

ReDim vtemp(1, 1 To NUMBER_OF_PROPERTIES)

  Set objWMI = GetAnotherWMIService

  Set colFiles = objWMI.ExecQuery _
             ("Select * from CIM_DataFile where Name = " & "'" & fileName & "'")

  For Each objFile In colFiles
    With objFile
      vtemp(1, 1) = .CreationDate
      vtemp(1, 2) = .Extension
      vtemp(1, 3) = .fileName
      vtemp(1, 4) = .FileSize
      vtemp(1, 5) = .FileType
      vtemp(1, 6) = IIf(Len(.InUseCount & vbNullString) = 0, 0, .InUseCount)
      vtemp(1, 7) = .LastAccessed
      vtemp(1, 8 ) = .LastModified
      vtemp(1, 9) = .Path
      vtemp(1, 10) = .Readable
      vtemp(1, 11) = .Writeable
    End With
  Next objFile

GetFileInfo = vtemp

End Function

Sample usage

Sub TestDataFileQuery()

Dim str As String
Dim varr() As String

str = "C:\\Users\\Jimmy Pena\\MyFile.txt"

varr = GetFileInfo(str)

Debug.Print "Is file writeable? Answer: " & varr(11)

End Sub

Site last updated: May 17, 2012

Excel School