【问题标题】:How Can I Remove The 'file:\\' From the Return Value of Path.GetDirectoryName() in C#如何从 C# 中 Path.GetDirectoryName() 的返回值中删除 'file:\\'
【发布时间】:2011-02-26 05:03:22
【问题描述】:
string path = Path.GetDirectoryName(
                     Assembly.GetAssembly(typeof(MyClass)).CodeBase);

输出:

文件:\d:\learning\cs\test\test.xml

仅返回 d:\learning\cs\test\test.xml

的最佳方法是什么

file:\\ 会在我调用 doc.Save(returnPath) 时抛出异常,但是 doc.Load(returnPath);效果很好。谢谢。

【问题讨论】:

标签: c# path


【解决方案1】:
string path = new Uri(Assembly.GetAssembly(typeof(MyClass)).CodeBase).LocalPath;

【讨论】:

  • 我想补充一点,虽然 Chris 的解决方案被标记为 Answer,但 Matthew 的解决方案实际上为标题中的问题和我的问题提供了适当的解决方案:How to convert a file:// 样式路径到 C:\ 样式路径。谢谢马修!
  • 这种方法的问题是,如果你有任何无效的 URI 字符(例如,尖锐的 #),这将被 new Uri() 函数省略,你的路径将是错误的。您必须使用 WebUtility.UrlEncode 之类的东西才能正确获得正确的路径。
  • @Fabiano 我有一个带 # 的路径,使用 UrlEncode 在运行 new Uri(WebUtility.UrlEncode(myWeirdPath)) 时会引发异常;替代品?
【解决方案2】:

如果你想要那个类的程序集目录,你可以使用Assembly.Location属性:

string path = Path.GetDirectoryName(Assembly.GetAssembly(typeof(MyClass)).Location);

不过,这与CodeBase 属性并不完全相同。 Location 是“包含清单的已加载文件的路径或 UNC 位置”,而 CodeBase 是“最初指定的程序集的位置,例如,在 AssemblyName 对象中”。

【讨论】:

  • 感谢您提供简单但完美的解决方案。 @all,谢谢。
  • Location 是卷影复制后的程序集位置,而 CodeBase 是卷影复制发生之前的原始位置。因此,如果启用了卷影复制,并且您想要原始位置,则必须使用 CodeBase。
【解决方案3】:
  System.Uri uri = new System.Uri(Assembly.GetAssembly(typeof(MyClass)).CodeBase);
  string path = Path.GetDirectoryName(uri.LocalPath);

【讨论】:

  • 我注意到如果我使用 System.Uri,路径中的空格被替换为“%20”
  • @AlexKoshulyan - 对于 Uri 的某些属性,您是正确的,例如 AbsolutePath。但 Uri.LocalPath 似乎没有用 %20 替换空格 - 至少从我所见。
【解决方案4】:

我的第一种方法是这样的......

path = path.Replace("file://", "");

【讨论】:

  • 虽然这可能会回答 OP 手头的问题,但这是一个糟糕的解决方案。 uri 类处理更多的极端情况。
  • @nawfal - “uri 类处理更多的极端情况”......它还引入了自己的大量极端情况。例如,如果您的程序集的 CodeBase 在 file:///c:/temp/#my_test#/WindowsFormsApplication1/WindowsFormsApplication1/bin/Debug/WindowsFormsApplication1.EXE 中,并且您将该 CodeBase 值传递给 Uri 构造函数,您会得到 c :\\temp 用于 uri.LocalPath。哈希字符导致它无法像人们希望的那样工作。
【解决方案5】:

使用substring字符串的方法来获取file:\后面的文件名

【讨论】:

    猜你喜欢
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-24
    • 2018-03-07
    • 1970-01-01
    • 2021-12-13
    相关资源
    最近更新 更多