Saturday, November 5, 2011

How to Read the Contents of the Directory in Visual Basic .Net


In Visual Basic 6, it is awkward to read the contents of a directory: you have to call the Dir$ function repeatedly. This function returns the name of the first file in the directory, and then the next, and so on. You cant examine two directories at the same time because Dir$ tracks only the file it has enumerated for the current directory. In Visual Basic .NET, getting the list of files in a directory is much simpler. Use the System.IO.Directory.GetFiles method to return an array of filenames. The following sample code is from the Dashboard.GetSubForms method in the DynamicApp project:
Dim filePathArray() As String
filePathArray = System.IO.Directory.GetFiles(myDirectory(), "*.dll")
After this code runs, the filePathArray variable is filled with an array of file paths, such as
C:DynamicShellbinGraphicsFeatures.dll
The System.IO namespace contains many other useful functions as well. For example, System.IO.Path.GetDirectoryName returns the directory name from a file path. The code
MsgBox(System.IO.Path.GetDirectoryName( _
   "C:DynamicShellbinGraphicsFeatures.dll"))
shows C:DynamicShell in the message box. In a similar vein, the System.IO.Path.GetFileName methodreturns the filename of a file path. For example, the code
MsgBox(System.IO.Path.GetFileName( _
  "C:DynamicShellbinGraphicsFeatures.dll"))
shows GraphicsFeatures.dll in the message box. Another useful function is System.Reflection.Assembly.GetExecutingAssembly. This last method returns the file path of theapplication. DynamicApp passes the file path to System.IO.Path.GetDirectoryName to get the applications directory, which is how it knows where to look for DLLs.

No comments:

Post a Comment