Pages

Wednesday, May 8, 2013

Access special folders without legacy COM references (Visual Basic)

One of the tasks that you’ve probably had to do once or twice is access files in special folders like Desktop, Favorites, and My Documents. The problem with accessing these folders is that they are user and operating system dependent, so you can’t just hardcode a path. For example, the folder may be at C:\Documents and Settings\user1 for one user and H:\Documents and Settings\user2 for another.

In VB 2003, you could access a special folder by referencing the Windows Script Host Object Model and using code similar to the following:

Dim wsh As New IWshRuntimeLibrary.WshShell
Dim myFavorites As String = CType(wsh.SpecialFolders.Item("MyDocuments"), String)


In VB 2005, you don’t need any of this. You can simply use the My class, like so:

Dim strMyDocuments As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.