Assembly.CodeBase: when is it not a file-URI?
Assembly.Location provides a simple assembly path. Unfortunately, when run in a shadow environment like unit test or ASP.NET, this is empty. Hovever, the Codebase property is available and provides a URI that can be used instead. In what cases does it not return a URI starting with file:///
? Or, in other words: what are the cases when this won't work or return unusable results?
Assembly assembly = GetType().Assembly;
Uri codeBaseUri = new Uri(assembly.CodeBase);
string path = codeBaseUri.LocalPath;
+2
source to share
2 answers
It is possible to load assemblies directly over HTTP, for example to a ClickOnce deployment:
Assembly assembly = Assembly.LoadFrom("http://server/app.dll");
Uri codeBaseUri = new Uri(assembly.CodeBase);
Debug.Assert(codeBaseUri.Scheme == "http");
Debug.Assert(codeBaseUri.LocalPath == "");
Debug.Assert(assembly.Location == "");
+3
source to share
Also, # char is treated as a chunk separator. See http://blogs.msdn.com/ncl/archive/2010/02/23/system-uri-faq.aspx (section 9) for a quick explanation.
Use Assembly.EscapedCodeBase instead of Assembly.CodeBase to fight it.
0
source to share