如何从C#中Path.GetDirectoryName()的返回值中删除'file:\\'

Nan*_* HE 26 c# path

string path = Path.GetDirectoryName(
                     Assembly.GetAssembly(typeof(MyClass)).CodeBase);
Run Code Online (Sandbox Code Playgroud)

输出:

文件:\ d:\学习\ CS \测试\的test.xml

返回d:\ learning\cs\test\test.xml的最佳方法是什么

file:\\doc.Save(returnPath)但是doc.Load(returnPath),当我打电话时会抛出异常; 效果很好.谢谢.

Mat*_*hen 56

string path = new Uri(Assembly.GetAssembly(typeof(MyClass)).CodeBase).LocalPath;
Run Code Online (Sandbox Code Playgroud)

  • 我想补充一点,虽然Chris的解决方案被标记为Answer,但是Matthew的解决方案实际上为标题和我的问题中的问题提供了正确的解决方案:如何将file:// style path转换为a C:\ style path.谢谢马修! (6认同)

Chr*_*ich 16

如果需要该类程序集的目录,可以使用该Assembly.Location属性:

string path = Path.GetDirectoryName(Assembly.GetAssembly(typeof(MyClass)).Location);
Run Code Online (Sandbox Code Playgroud)

但这与CodeBase财产并不完全相同.它Location是"包含清单的加载文件的路径或UNC位置",而" CodeBase是最初指定的程序集的位置,例如,在AssemblyName对象中".

  • 位置是影子复制后的装配位置,而CodeBase是原始位置,在影子复制发生之前.因此,如果启用了卷影复制,并且您需要原始位置,则必须使用CodeBase. (4认同)

Moe*_*sko 8

  System.Uri uri = new System.Uri(Assembly.GetAssembly(typeof(MyClass)).CodeBase);
  string path = Path.GetDirectoryName(uri.LocalPath);
Run Code Online (Sandbox Code Playgroud)