Mono - 从 Path.GetDirectoryName 返回的路径无效

Mono - invalid path returned from Path.GetDirectoryName

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

它确实适用于 windows。 在单声道版本 4.2.1 上,结果是:

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

这是一个错误,还是我做错了什么?

我找到了解决方案。

Uri 应该直接从 CodeBase 构造,因为它 returns Uri 格式的路径。然后 Uri.LocalPath returns 程序集的本地路径(以路径格式),这里是可以使用 GetDirectoryName 的地方。

我做了扩展:

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);
    }
}