about C#, C++, Java, sql, java script etc.

Sunday, January 24, 2010

Convert relative path to absolute in VB.NET

Recently I've found a good way to get an absolute path out of a base and relative paths. Before I used the method Directory.SetCurrentDirectory(). But changing the current directory to a base directory, then to one in a relative path and finally reading the resulting path with Directory.GetCurrentDirectory() is kind of clumsy.
.NET provides a better solution in the class Uri:

 ''' <summary>
 ''' Constructs and returns an absolute path if <paramref name="absoluteOrRelativePath"/> is a relative path.
 ''' Otherwise <paramref name="absoluteOrRelativePath"/> is returned.
 ''' </summary>
 ''' <param name="basePath"></param>
 ''' <param name="absoluteOrRelativePath"></param>
 ''' <returns></returns>
 Function GetAbsolutePath(ByVal basePath As String, ByVal absoluteOrRelativePath As String) As String
   Dim baseUri As Uri = New Uri(basePath)
   Dim resultUri As Uri = baseUri

   Uri.TryCreate(baseUri, absoluteOrRelativePath, resultUri)

   Return resultUri.AbsolutePath
 End Function 

Examples:
GetAbsolutePath("c:\temp\", "cache/") c:/temp/cache/
GetAbsolutePath("c:\windows\app.conf", "system32/") c:/windows/system32/
GetAbsolutePath("c:\windows\temp\", "d:\cache\") d:/cache/

1 comment:

  1. ...or just use:

    system.io.Path.GetFullPath(system.io.Path.Combine("C:\folder1\folder2\folder3\folder4\folder5","..\..\..\..\..\smallpic.jpg"))

    ReplyDelete