格式字符串包含“{”时的String.Formatexception

我使用的是VSTS 2008 + C#+ .Net 2.0。 当执行以下语句时,从String.Format语句中抛出FormatException,任何想法有什么问题?

这是获取我正在使用的template.html的地方。 我想在template.html中格式化此部分m = {0}。

string template = String.Empty; using (StreamReader textFile = new StreamReader("template.html")) { template = textFile.ReadToEnd(); String.Format(template, "video.wmv"); } 

http://www.mediafire.com/download.php?u4myvhbmmzg

编辑1:

这是我的template.html的内容,

     Silverlight Project Test Page   html, body { height: 100%; overflow: auto; } body { padding: 0; margin: 0; } #silverlightControlHost { height: 100%; }   function onSilverlightError(sender, args) { var appSource = ""; if (sender != null && sender != 0) { appSource = sender.getHost().Source; } var errorType = args.ErrorType; var iErrorCode = args.ErrorCode; var errMsg = "Unhandled Error in Silverlight 2 Application " + appSource + "\n" ; errMsg += "Code: "+ iErrorCode + " \n"; errMsg += "Category: " + errorType + " \n"; errMsg += "Message: " + args.ErrorMessage + " \n"; if (errorType == "ParserError") { errMsg += "File: " + args.xamlFile + " \n"; errMsg += "Line: " + args.lineNumber + " \n"; errMsg += "Position: " + args.charPosition + " \n"; } else if (errorType == "RuntimeError") { if (args.lineNumber != 0) { errMsg += "Line: " + args.lineNumber + " \n"; errMsg += "Position: " + args.charPosition + " \n"; } errMsg += "MethodName: " + args.methodName + " \n"; } throw new Error(errMsg); }     

感谢avvance,乔治

猜测,html包含javascript或其他大括号( {} ),它们都需要加倍(到{{}} )才能与string.Format一起使用。 我希望有一个不同的(更明显的)令牌可以按顺序排列,即%%FILENAME%% 。 然后使用正则表达式或string.Replace

如果你有一个标签, string.Replace很好; 如果你有很多,有正则表达式和MatchEvaluator技巧可能会有所帮助 – 就像这样但具有不同的正则表达式模式。


添加示例html后更新:我肯定会使用不同的令牌; 在最基本的层面:

  

 template = template.Replace("%%FILENAME%%", "video.wmv"); 

您的模板包含需要转义的{}字符,否则会混淆String.Format 。 使用{{}}转义它们。 或者,使用不同的机制,如String.Replace

string.Format()不处理格式字符串中的{} 。 您需要在template.html文件中的任何位置替换{ with {{} with }} 。 除了使用{0}占位符的单个位置。

不是很优雅。

相反,请考虑使用模板引擎。 有关建议,请参见http://csharp-source.net/open-source/template-engines 。

下一个最佳解决方案是使用正则表达式(使用MatchEvaluator)或string.Replace(),如其他答案所示。

编辑:

这是使用StringTemplate模板引擎的示例:

 StringTemplate htmlpage = new StringTemplate(File.ReadAllText("template.html")); htmlpage.SetAttribute("content", "video.wmv"); Console.WriteLine(htmlpage.ToString()); 

更改template.html文件中的一行:

从:

  

至:

  

当模板引擎在模板中遇到$content$时,它会将其替换为您使用代码设置的’content’属性的值。

使用StringTemplate,您可以在模板中执行简单的循环和条件。 请参阅文档 。

Wat是’template’变量的内容?

很难说你的代码有什么问题,但可能是模板变量不包含作为占位符的字符串。 (比如“这是一些字符串{0}”)。

我认为您应该使用IDE提供的工具:调试代码,使用watch来检查模板变量的内容。

什么是模板文件?

如果有大括号{int}的大括号,或者格式语句的参数不止,则会引发exception。

exception中的消息是什么?

这是你的Css。 正如其他人所提到的,你需要做一个正则表达式替换,或者连续一堆String.Replace命令用%% VARIABLE_NAME %%标记变量并使用字符串替换来替换它们