简体   繁体   中英

Getting Input string was not in a correct format while using string.Format

I am trying to use string.format to fill some values in a string template, below is the string value:

{
\"version\":\"9.40.20153.0\",\"sheetCount\":1,
\"sheets\":{

\"{0}\":
{
\"name\":\"{1}\",
\"rowCount\":{2},
\"columnCount\":{3},
\"colHeaderData\":{
\"dataTable\":{
{4}
}
        },
\"data\":{
\"dataTable\":{
                 {5}
        },
    \"index\":0
    }
  }
}

And below is the code for calling the string.Format method:

string newString=SB.AppendLine(string.Format(genericTemplate, sheetName,columnCount, rowCount,3,5,6)).ToString();

It has become quite frustrating now :(. Please Help!!

You have to escape all the curly brackets that are not used for formatting. This is done by simply duplicating each curly bracket.

For example the first line and last line should look like this:

{{
}}

while this line has to remain as it is:

\"{0}\":

var genericTemplate = @"
{{
""version"":""9.40.20153.0"",""sheetCount"":1,
""sheets"":{{

""{0}"":
{{
""name"":""{1}"",
""rowCount"":{2},
""columnCount"":{3},
""colHeaderData"":{{
""dataTable"":{{
{4}
}}
        }},
""data"":{{
""dataTable"":{{
                 {5}
        }},
    ""index"":0
    }}
  }}
}}";
var newString = string.Format(genericTemplate, "arg1", "arg2", "arg3", "arg4", "arg5", "arg6");

This is happening because you are trying to use curly braces in the string. You need to escape those as another answer has stated. Your better option may be to create an object for this and serialize it to JSON.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM