tags:

views:

422

answers:

2

I have C# code that is trying to get the LocalPath for a executing assembly using the following line of code

Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath;

This piece of code performs fine for all the variety of paths. It started to fail giving the right AbsolutePath and Localpath because the executing assembly path contained a # in it.

Assembly.GetExecutingAssembly().CodeBase gives "C:\c#\ExcelAddin1.1.0\GSRExcelPlugin\bin\Debug\Common.dll"

But new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath gives "C:\c" while it should have given "C:\c#\ExcelAddin1.1.0\GSRExcelPlugin\bin\Debug\".

Is there something that I need to handle or is there something wrong the way Uri class is used?

Please suggest.

If this is a .net framework issue, how should I report this issue to Microsoft?

Thanks in advance.

+1  A: 

I assume The URI functions are stripping away everything after the sharp # because it thinks its an anchor.

URI are designed for identifying resources on the internet, so your # character would be an illegal character in the middle of any URI.

Take even this question for example, the Title is

System.Uri fails to give correct AbsolutePath and LocalPath if the Path contains “#”

but the end of the URL has the "#" stripped away

system-uri-fails-to-give-correct-absolutepath-and-localpath-if-the-path-contains

Why do you need to convert it into a URI anyway. The only difference between these 3 console.writelines is the fact that the first two are prefixed with File:///

Console.WriteLine(Assembly.GetExecutingAssembly().CodeBase);  // 1
Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase);
Console.WriteLine(uri);                                       // 2
Console.WriteLine(uri.LocalPath);                             // 3
Eoin Campbell
A: 
System.IO.FileInfo logger = new System.IO.FileInfo(Path.Combine(Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath), "settings.config"));

Using EscapedCodeBase instead of CodeBase solves the problem. I dint realize that this was already handled until I stumbled on it.:)