KnowDotNet NetRefactor

Using the System.IO Namespace - The Path Class

by Les Smith
Print this Article Discuss in Forums

The System.IO Namespace is one of the greatest time-savers in the .NET Framework.  Not only is it a big time-saver, but it removes a lot of the nitty-gritty "bit-fiddling" involved with working with files, filenames, paths, etc.  Since writing Development Tools has always been one of my hobbies, I have done a lot of work with source files; reading, writing, parsing code, parsing filenames, paths, extensions, etc.  

To parse paths, filenames, and extensions in any version of VB prior to the advent of the .NET Framework was always a pain.  Not only was it time-consuming, but it was fraught with errors.  The following code snippets show the VB6 way and the .NET way to manipulate this type of data.  What a difference!  Although the following examples are all written in VB.NET, they will work exactly the same in C#.

By the way, if you are like me, and have been coding in .NET for over two years, you are still learning new methods for doing things because the .NET Framework is so huge and so powerful.  First, I will set up some variables to be used in all of the code examples, as I explore most of the methods of the System.IO.Path Class.  I have included a MsgBox display of all results so that you can simply plug the code into a program and see the results of each snippet.


      Dim TestPath As String
      Dim nPos As Integer
      Dim sFileName As String
      Dim sFullPath As String
      Dim sExt As String
      TestPath = "C:\TESTPATH\TESTPATH2\FILENAME.TXT"

In the following example, I want to extract only the path from a string which includes a path and a filename.  In VB6, I must find the last separator in order to delete the filename from the rest of the path.

      ' get path only in vb6
      nPos = InStrRev(TestPath, "\")
      sFullPath = Mid(TestPath, 1, nPos - 1)
      MsgBox(sFullPath)

      
' get path only in .NET
      sFullPath = Path.GetDirectoryName(TestPath)
      MsgBox(sFullPath)

Next, I want to retrieve just the file extension from a path and filename.

      ' get ext in VB6
      nPos = InStrRev(TestPath, ".")
      sExt = Mid(TestPath, nPos)
      MsgBox(sExt)

      
' get ext in .NET
      sExt = Path.GetExtension(TestPath)
      MsgBox(sExt)

Now, I want to get the filename only from the path and filename.

      ' get filename in VB6
      nPos = InStrRev(TestPath, "\")
      sFileName = Mid(TestPath, nPos + 1)
      nPos = InStr(sFileName, ".")
      sFileName = Mid(sFileName, 1, nPos - 1)
      MsgBox(sFileName)

      
' get filename without ext in .NET
      sFileName = Path.GetFileNameWithoutExtension(TestPath)
      MsgBox(sFileName)

If I need to get the root directory from a path, there is an easier way to do it in .NET than in VB6.

      ' get the root directory of a path in VB6
      nPos = InStr(TestPath, "\")
      sRoot = Mid(TestPath, 1, nPos)
      
' could have used, but still not as simple as
      ' the .NET way
      sRoot = Mid(TestPath, 1, InStr(TestPath, "\"))
      MsgBox(sRoot)

      
' get the root directory
      sRoot = Path.GetPathRoot(TestPath)
      MsgBox(sRoot)

Let's suppose that I want to switch file extensions of the filename in a path.  Although it is obvious, in the following example, what the original extension is, that is not always the case.  This example again contrasts VB6 against .NET

      ' how about switching extensions, lets say we have
      ' a .txt file and we want to create a .XML filename to
      ' match the wav file name
      ' in vb6 code...assuming we don't know the original ext
      Dim xmlFN As String
      nPos = InStrRev(TestPath, ".")
      xmlFN = Mid(TestPath, 1, nPos) & "xml"
      MsgBox(xmlFN)

      
' now switch the extension in .NET
      xmlFN = Path.ChangeExtension(TestPath, "xml")
      MsgBox(xmlFN)

The classic example, that is constantly dogging me, is where I need to append a filename.ext to a path, but I don't know whether there is a "\" at the end of the path or not.  Therefore, before .NET, I had to test for it before I could concatenate the two strings.  The Combine method of the Path class handles the problem automatically.

      Dim sPath As String
      sPath = "c:\test"
      
If Microsoft.VisualBasic.Right(sPath, 1) <> "\" Then
         sPath = sPath & "\"
      
End If
      sPath = sPath & "fn.ext"
      MsgBox(sPath)

      
' the .NET way
      sPath = "c:\test"
      sPath = Path.Combine(sPath, "fn.ext")
      MsgBox(sPath)

Ever have to create a unique file name so that you could write a temporary file and be assured that you would not conflict with other applications using the same temporary file name?  Again, .NET comes to the rescue.

      ' try creating a unique file name for a temporary
      ' file in VB6.  Here is some typical code I have used
      ' numerous times.
      Dim sFN As String
      Dim h As Integer
      h = FreeFile()

      
Do
         sFN = "c:\Temp" & Format(Now, "HHmmss")
        
Try
            FileOpen(h, sFN, OpenMode.Output, OpenAccess.Write)
        
Catch ex As Exception
        
End Try
         If IO.File.Exists(sFN) Then
            Exit Do
         End If
      Loop
      MsgBox(sFN)

      
' now for the real time saver, creating a
      ' unique file name in .NET
      Dim sTempFN As String = Path.GetTempFileName()
      MsgBox(sTempFN)

The System.IO Namespace is very large.  In this article, I have just explored one small part of it, the Path Class.  In future articles, I will continue to explore this great Namespace.

Top of Page

Writing Add-Ins for Visual Studio .NET
Writing Add-ins for Visual Studio .NET
by Les Smith
Apress Publishing