Monday, January 05, 2009 Register  Login
RSS Feeds
Categories
  
Blog Archives
  
Blog

Code to convert a file path to a file URL

I had an interesting time fixing a bug in PainlessSVN when using UNC paths. I had a function in SVNManagerLib that converted the path to the file:/// format. This is what the original looked like: 

public static string PathToFileUrl( string pathToConvert )
{
     string parsedDir = "";
     StringBuilder arg = new StringBuilder();
 
     parsedDir = pathToConvert.Replace("\\", "/");
 
     arg.Append("file:///");
     arg.Append((char)34);
     arg.Append(parsedDir);
     arg.Append((char)34);
 
     return arg.ToString();
}

That didn't quite work. I did some Googling and found the answer. Let me post the code first then, I'll explain:

 

public static string PathToFileUrl( string pathToConvert )
{
    UriBuilder fileURL = new UriBuilder( pathToConvert );
 
    return fileURL.ToString();
}

The UriBuilder is a special class that helps build valid URIs. I keep learning this lesson over and over... Don't re-invent the wheel, just use what the .NET framework already has. There's quite a bit in there. I've been using .NET since 2002, and I keep finding these little nuggets.

posted @ Tuesday, October 16, 2007 8:11 PM by Hector Sosa, Jr

Previous Page | Next Page

COMMENTS

Name (required)

Email (required)

Website

Enter the code shown above:

Terms Of Use | Privacy Statement | SystemWidgets
Copyright 2002-2008 by SystemWidgets