{ literal with AppendFormat

R

ramhog

Hello all,
I would like to use AppendFormat to replace tokens in a string with
actual string values. The problem I am running into however is that my
string uses {} around a string that I do not want formatted. Is there
a way to tell the AppendFormat method not to see certain {} as a token
to be replaced?

In the example here, I want to replace {0} with the string "Test" but
leave the string {SQL Server} just like it is in the string.

string MBConnectBase = @"{0} and {SQL Server}";
try
{
System.Text.StringBuilder builder = new
System.Text.StringBuilder();

string format = MBConnectBase;
builder.AppendFormat(format, "Test");

System.Diagnostics.Debug.WriteLine(builder.ToString());
}
catch(System.Exception exc)
{
MessageBox.Show(exc.Message.ToString());
}
 
C

Carl Daniel [VC++ MVP]

ramhog said:
Hello all,
I would like to use AppendFormat to replace tokens in a string with
actual string values. The problem I am running into however is that my
string uses {} around a string that I do not want formatted. Is there
a way to tell the AppendFormat method not to see certain {} as a token
to be replaced?

In the example here, I want to replace {0} with the string "Test" but
leave the string {SQL Server} just like it is in the string.

string MBConnectBase = @"{0} and {SQL Server}";
try
{
System.Text.StringBuilder builder = new
System.Text.StringBuilder();

string format = MBConnectBase;
builder.AppendFormat(format, "Test");

System.Diagnostics.Debug.WriteLine(builder.ToString());
}
catch(System.Exception exc)
{
MessageBox.Show(exc.Message.ToString());
}

Just double-up the { }

string MBConnectBase = @"{0} and {{SQL Server}}";

-cd
 
R

ramhog

Thank you for your reply.
Is there an escape sequence or any other options. Just making sure I
have my bases covered.

- k
 
C

Carl Daniel [VC++ MVP]

ramhog said:
Thank you for your reply.
Is there an escape sequence or any other options. Just making sure I
have my bases covered.

The doubled {{ is the only escape sequence - no other characters besides { }
have specific meaning in a composite format string.

-cd
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top