How to avoid input string/StringBuilder in an incorrect format error in C#

Viewed 13523

I'm using a string builder to append text to string.

StringBuilder content = new StringBuilder(GetStartHTML("installation",string.Empty));
.......
content.AppendFormat("<td>" + idcStepEntity.Comment + "</td>");

Unfortunetly i cannot control what comes in from the customer as comment, so i they write something like : comment { commment] comment (and they often do) i get string was not in a correct format error. That mean i should not use a StringBuilder here? Should i usestring += otherstring or is there any other String class that can bu usefull here?

Thanks in advance :)

3 Answers

This error is possible only with StringBuilder.AppendFormat and if your string contains { or }. So the solution is to use StringBuilder.Append (as you don`t really use the format part):

content.Append("<td>" + idcStepEntity.Comment + "</td>");

Try this:

content.AppendFormat("<td>{0}</td>", idcStepEntity.Comment);

Note that, your exception is because your idcStepEntity.Comment may contain some block {}, then when you pass it into AppendFormat, the following overload will be used:

AppendFormat(string format, params object[] args);

That means it considers your idcStepEntity.Comment as the format string and there is not any arguments, that format string contains some invalid block {} and hence the exception is thrown.

Related