逃避'&'在App.Config CodeBase属性中的文件路径中

时间:2015-01-15 17:37:44

标签: c# .net xml app-config

假设您的路径中有一个带符号&的文件夹,并且您希望在此类文件夹中运行.NET应用程序。

AppDomain基目录不需要转义,它只能作为file:///T:/Te&st/ 对于appdomain的私有路径也是如此。貌似,.NET在URI中没有裸露的&符号问题 但是使用.exe.config app配置文件会很棘手。

它是一个XML文件,所以我直观地使用常规的XML转义,如下所示:

<cfg:codeBase version="6.0.0.0" href="file:///T:/Te&amp;st/Lib/JetBrains.Platform.Util.DLL" />

但是这在运行时失败了。从Fusion fuslogvw日志中我们可以了解到它将URI视为

LOG: Attempting download of new URL file:///T:/Test/Lib/JetBrains.Platform.Util.DL.

此处省略&,最后一个字符L也是如此。

通过实验,我发现转义U+0026 Ampersand字符的URI可以节省时间,如下所示:

<cfg:codeBase version="6.0.0.0" href="file:///T:/Te%26st/Lib/JetBrains.Platform.Util.DLL" />

XML转义的&符号会发生什么?哪个操作可能产生这样的效果,特别是丢弃最后一个字符?

除了&之外哪些路径合法的字符可能还需要转义?

构建正确转义的Uri对象的最一致方法是什么? (Uri::EscapeUriString不认为&需要任何转义

1 个答案:

答案 0 :(得分:0)

我想你已经有了一个带有属性值的变量。

string str = read_attriute_function(); // Your function to load the value as string

Dictionary<string, string> escape_sequences = new Dictionary<string, string>();

// add escape sequences to dictionary
escape_sequences.Add("&amp;", "%26");
escape_sequences.Add("#", "%23");


foreach (KeyValuePair<string, string> entry in escape_sequences)
    str = str.Replace(entry.Key, entry.Value);

你可以选择看看HttpUtility.HtmlDecode 对于所有转义字符,请查看this questionthis reference


如果我误解了你的问题,请纠正我:)