我的C#应用程序将双引号括起的完整路径写入文件,其中包含:
streamWriter.WriteLine("\"" + Application.ExecutablePath + "\"");
通常它有效,书面文件包含
"D:\Dev\Projects\MyApp\bin\Debug\MyApp.exe"
但是,如果我的应用程序的可执行路径包含#,则会发生奇怪的事情。输出变为:
"D:\Dev\Projects#/MyApp/bin/Debug/MyApp.exe"
#之后的斜线成为正斜杠。这会导致我正在开发的系统出现问题。
为什么会发生这种情况,有没有办法防止它比string更优雅。在写作之前更换路径?
答案 0 :(得分:9)
我只是查看了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和其他特殊情况的情况。我简化了最常见情况的代码。
答案 1 :(得分:1)
奇怪的错误/错误。除了使用替换函数或扩展方法始终返回正确的格式,您可以尝试使用
System.Reflection.Assembly.GetExecutingAssembly().Location
而不是ExecutablePath。