奇怪的C#路径问题

Rya*_*yan 18 c c# string path slash

我的C#应用​​程序将其双引号包围的完整路径写入文件,其中:

streamWriter.WriteLine("\"" + Application.ExecutablePath + "\"");
Run Code Online (Sandbox Code Playgroud)

通常它可以工作,写入的文件包含

"D:\Dev\Projects\MyApp\bin\Debug\MyApp.exe"
Run Code Online (Sandbox Code Playgroud)

但是,如果我的应用程序的可执行路径包含#,则会发生奇怪的事情.输出变为:

"D:\Dev\Projects#/MyApp/bin/Debug/MyApp.exe"
Run Code Online (Sandbox Code Playgroud)

#之后的斜线成为正斜杠.这会导致我正在开发的系统出现问题.

为什么会发生这种情况,有没有办法防止它比string更优雅.在写入前更换路径?

Eli*_*ing 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();
Run Code Online (Sandbox Code Playgroud)

该属性Assembly.CodeBase将该位置作为URI返回.就像是:

file:///C:/myfolder/myfile.exe

#是URI中的片段标记; 它标志着片段的开始.显然,Uri该类在解析时会改变给定的uri并再次转换回字符串.

由于Assembly.Location包含"正常"文件路径,我想你最好的选择是:

string executablePath = Assembly().GetEntryAssembly().Location;
Run Code Online (Sandbox Code Playgroud)

*)实现比这更复杂,因为它还处理有多个appdomains和其他特殊情况的情况.我简化了最常见情况的代码.