0
var codebase = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
var path = Path.GetDirectoryName(codebase);

It does work on windows. On mono version 4.2.1 the result is:

codebase: file:///home/...
path: file:/home/...

Is this a bug, or am I doing something wrong?

smokeing
  • 259
  • 1
  • 3
  • 13
  • Those are valid method returns and paths.... ? What are you expecting? – SushiHangover Dec 10 '15 at 18:25
  • URI class cannot parse path with only one "/" after file – smokeing Dec 10 '15 at 18:35
  • 1
    ahh, If you are looking to get the "path" of the assembly to then convert it into a Uri, use GetExecutingAssembly().Location. – SushiHangover Dec 10 '15 at 18:53
  • Thanks for tip. However is it normal that .NET version of GetDirectoryName returns path with "file://..." prefix and Mono version with "file:/..." ? – smokeing Dec 10 '15 at 21:35
  • 1
    The issue digs into how `hostname` is handled in file uri schemes and dealing with legacy paths (PathCreateFromUrl)... You should not get a single (file:/) but your asking it to convert file:/// that has an empty Authority/Host via a function that accepts a `path` string vs a URI scheme, thus is posix's it and strips the blank authority and removes the `name` and you are left with file:/xxx/... yuk... So instead of trying to understand RFC 1630 and RFC 1738 as it can might a head hurt, pass fully qualified paths, not a file uri, to those functions that expect a local or UNC path... – SushiHangover Dec 10 '15 at 23:16
  • Assembly.Location works on mono, but on Windows it always points to temp AppData/Local/Temp folder. I found my original solution (CodeBase) here http://stackoverflow.com/questions/864484/getting-the-path-of-the-current-assembly – smokeing Dec 11 '15 at 11:42

1 Answers1

1

I have found solution.

Uri should be constructed from CodeBase directly because it returns path in Uri format. Then Uri.LocalPath returns local path to assembly (in path format) and here is place where GetDirectoryName can be used.

I have made an extension:

using System;
using System.IO;
using System.Reflection;
public static class AssemblyExtensions
{
    public static string GetCodeBaseLocation(this Assembly assembly)
    {
        var uri = new Uri(assembly.CodeBase);
        return Path.GetDirectoryName(uri.LocalPath);
    }
}
smokeing
  • 259
  • 1
  • 3
  • 13