Graham
Graham

Reputation: 31

Escape character appears in the string

I am writing a piece of code in Visual c# 2010 to generate a string. This string needs to contain backslashes \ and speech marks ".

I have tried the following ways of doing this:

string StringOutputVariable;
string StringVariable = "hello world";
StringOutputVariable = "\"C:\\Program Files\\some program\\some program.exe\" " + StringVariable;

and

string StringOutputVariable;
string StringVariable = "hello world";
StringOutputVariable = @"""C:\Program Files\some program\some program.exe"" " + StringVariable;

however they both put the escape characters in the output string:

\"C:\\Program Files\\some program\\some program.exe\" hello world

and

\"C:\\Program Files\\some program\\some program.exe\" hello world

what I want it to output is:

"C:\Program Files\some program\some program.exe" hello world

Why does my code output the escape characters into the string?

Thanks in advance Graham

Upvotes: 3

Views: 1132

Answers (4)

Soner Gönül
Soner Gönül

Reputation: 98858

Debugger shows strings if they have string literals.

Try like this;

    string StringOutputVariable;
    string StringVariable = "hello world";
    StringOutputVariable = "\"" + @"C:\Program Files\some program\some program.exe\" + "\"" + StringVariable;
    Console.WriteLine(StringOutputVariable);

Here is a DEMO.

Output is:

"C:\Program Files\some program\some program.exe\"hello world

Upvotes: 1

Hossein Narimani Rad
Hossein Narimani Rad

Reputation: 32521

try this:

string path = @"C:\Program Files\some program\some program.exe";

string result = string.Format("{0}{1}{0} hello world", "\"", path);

// you can check it: MessageBox.Show(result);

Upvotes: 1

Joey
Joey

Reputation: 354824

I assume you're looking at the strings in the debugger. The debugger will show strings as if they were string literals, that is, with quotation marks and backslashes escaped. The string is like you intended it to be.

You can easily check by simply printing the string to the console or putting it somewhere on a Form.

Upvotes: 2

Vincent James
Vincent James

Reputation: 1158

StringOutputVariable = "\"" +
        @"C:\Program Files\some program\some program.exe\" + "\" " + StringVariable;

Upvotes: 2

Related Questions