6

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.

riQQ
  • 9,878
  • 7
  • 49
  • 66
Scott Lawrence
  • 6,993
  • 12
  • 46
  • 64
  • Scott's answer is what you want, but I'm out of votes. – MusiGenesis Nov 10 '08 at 19:20
  • Does this answer your question? [How can I convert Assembly.CodeBase into a filesystem path in C#?](https://stackoverflow.com/questions/4107625/how-can-i-convert-assembly-codebase-into-a-filesystem-path-in-c) – StayOnTarget Mar 06 '22 at 14:34

4 Answers4

18

Try looking at the Uri.LocalPath property.

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);
}
Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
Scott Dorman
  • 42,236
  • 12
  • 79
  • 110
3

I looked for an answer a lot, and the most popular answer is using Uri.LocalPath. But System.Uri fails to give correct LocalPath if the Path contains “#”. Details are here.

My solution is:

private static string ConvertUriToPath(string fileName)
{
   Uri uri = new Uri(fileName);
   return uri.LocalPath + Uri.UnescapeDataString(uri.Fragment).Replace('/', '\\');
}
Community
  • 1
  • 1
Artsiom
  • 31
  • 1
0

Can you just use Assembly.Location?

Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393
  • 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 Lawrence Nov 10 '08 at 22:16
  • 1
    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 Nov 12 '08 at 15:11
  • Assembly.Current.Location or Assembly.GetExecutingAssembly().Location – Owen Johnson Apr 29 '13 at 19:03
0

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
  • 26,542
  • 16
  • 152
  • 170