我的 C# 应用程序将其用双引号括起来的完整路径写入文件,其中:
streamWriter.WriteLine("\"" + Application.ExecutablePath + "\"");
正常工作,写入的文件包含
"D:\Dev\Projects\MyApp\bin\Debug\MyApp.exe"
但是,如果我的应用程序的可执行路径包含#,就会发生奇怪的事情。输出变为:
"D:\Dev\Projects#/MyApp/bin/Debug/MyApp.exe"
# 之后的斜杠变成正斜杠。这会导致我正在开发的系统出现问题。
为什么会这样,有没有比string.replacing the path before writing更优雅的方法来防止呢?
最佳答案
我刚刚查看了 Application.ExecutablePath
的源代码,实现基本上是这样的*:
Assembly asm = Assembly.GetEntryAssembly();
string cb = asm.CodeBase;
var codeBase = new Uri(cb);
if (codeBase.IsFile)
return codeBase.LocalPath + Uri.UnescapeDataString(codeBase.Fragment);
else
return codeBase.ToString();
Assembly.CodeBase
属性将以 URI 的形式返回位置。像这样的东西:
file:///C:/myfolder/myfile.exe
#
是 URI 中的片段标记;它标志着片段的开始。显然,Uri
类在解析并再次转换回字符串时会更改给定的 uri。
由于 Assembly.Location
包含“正常”文件路径,我想您最好的选择是:
string executablePath = Assembly().GetEntryAssembly().Location;
*) 实现比这个更复杂,因为它还要处理存在多个appdomains等特殊情况。我针对最常见的情况简化了代码。
关于c# - 奇怪的 C# 路径问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12945805/