Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

c#

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 :)

like image 963
Margo Avatar asked Dec 02 '22 21:12

Margo


1 Answers

Having an unescaped "{" or "}" in the 1st argument of String.Format() will cause this exception.

This will cause the exception to be raised:

Microsoft.VisualBasic.MsgBox(String.Format("{"))

This is OK:

Microsoft.VisualBasic.MsgBox(String.Format("{0}", "{"))

Solution:

To escape "{" use "{{" and to escape "}" use "}}. Depending on your implementation, this could work for you.

Dim s As String = "{Hello}"
s = s.Replace("{", "{{")
s = s.Replace("}", "}}")

Stack trace:

It may appear in the stack trace to be a StringBuilder error because String.Format internally implements System.Text.StringBuilder, but you will get this exception even if you never use a StringBuilder in your project.

System.FormatException: Input string was not in a correct format.
    at System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
like image 73
Lakey Avatar answered Mar 09 '23 01:03

Lakey