Practical Web Programming

Thursday, January 31, 2008

How to Get the File Information Using API in Visual Basic

This function takes a passed filename as an argument and returns the description of that file. For example, if you pass the filename "c:\windows\sys.com" to the function, it will return the string "MS-DOS Application". If the file doesn'texist, it will return a blank type information.

NOTE: To see the result, copy and paste the code below in the
declaration section of a form.

'Constants declaration
Const SHGFI_DISPLAYNAME = &H200
Const SHGFI_TYPENAME = &H400
Const MAX_PATH = 260
Private Type SHFILEINFO
hIcon As Long ' out: icon
iIcon As Long ' out: icon index
dwAttributes As Long ' out: SFGAO_ flags
szDisplayName As String * MAX_PATH ' out: display name (or path)
szTypeName As String * 80 ' out: type name
End Type

'API declaration
Private Declare Function SHGetFileInfo Lib "shell32.dll" Alias _
"SHGetFileInfoA" (ByVal pszPath As String, _
ByVal dwFileAttributes As Long, _
psfi As SHFILEINFO, ByVal cbFileInfo As Long, _
ByVal uFlags As Long) As Long

'Gets the information of the file passed to it
Private Function GetFileInfo(strFileName) As SHFILEINFO
Dim lngRetVal As Long
Dim fileInfo As SHFILEINFO

lngRetVal = SHGetFileInfo(strFileName, 0, fileInfo, Len(fileInfo), _
SHGFI_DISPLAYNAME Or SHGFI_TYPENAME)
GetFileInfo = fileInfo
End Function

'This fucntion is used to strip al the unnecessary chr$(0)'s
Private Function StripTerminator(sInput As String) As String
Dim ZeroPos As Integer
'Search the position of the first chr$(0)
ZeroPos = InStr(1, sInput, vbNullChar)
If ZeroPos > 0 Then
StripTerminator = Left$(sInput, ZeroPos - 1)
Else
StripTerminator = sInput
End If
End Function

Private Sub Form_Load()
Dim fileInfo As SHFILEINFO

fileInfo = GetFileInfo("c:\autoexec.bat")
MsgBox "Displayname: " & StripTerminator(fileInfo.szDisplayName) & _
vbNewLine & _
"Typename: " & StripTerminator(fileInfo.szTypeName)
End Sub

0 comments:

Recent Post