views:

609

answers:

3

I was looking for something like Server.MapPath in the ASP.NET realm to convert the output of Assembly.GetExecutingAssembly().CodeBase into a file path with drive letter.

The following code works for the test cases I've tried:

private static string ConvertUriToPath(string fileName)
{
    fileName = fileName.Replace("file:///", "");
    fileName = fileName.Replace("/", "\\");
    return fileName;
}

It seems like there should be something in the .NET Framework that would be much better--I just haven't been able to find it.

A: 

Can you just use Assembly.Location?

Kent Boogaart
I can't use Assembly.Location because it's non-static and the method where I'd need to make the call from is static.
Scott A. Lawrence
Assembly.Location may not be what you're looking for, but it's not because it's a non-static method. Remember that you can instantiate new object within a static member.
akmad
+10  A: 

Try looking at the Uri.LocalPath method.

private static string ConvertUriToPath(string fileName)
{
   Uri uri = new Uri(fileName);
   return uri.LocalPath;

   // Some people have indicated that uri.LocalPath doesn't 
   // always return the corret path. If that's the case, use
   // the following line:
   // return uri.GetComponents(UriComponents.Path, UriFormat.SafeUnescaped);
}
Scott Dorman
A: 

Location can be different to CodeBase. E.g. for files in ASP.NET it likely to be resolved under c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET. See "Assembly.CodeBase vs. Assembly.Location" http://blogs.msdn.com/suzcook/archive/2003/06/26/57198.aspx

Michael Freidgeim