-4

I have got the string:

string test = "\test.xml";

how can I print it out as: \test.xml

kimliv
  • 427
  • 1
  • 8
  • 25
  • string test = "\\test.xml"; – Rahul Tripathi Feb 25 '14 at 12:04
  • 1
    Just a quick remark: the only reason you were able to compile this code at all is that "\t" is escape sequence for a tab. – Dirk Feb 25 '14 at 12:05
  • 1
    Who downvoted this? You don't have to google everything you know! What's wrong with asking simple questions on SO? – Alex Feb 25 '14 at 12:06
  • 2
    @Alex Asking requires another one to spend time to answer, searching for it first only requires yours. I would call it a common courtesy to search first. If you hover over the downvote button you see when you should downvote a question: "This question doesn't show any research effort; ...". Asking simple questions is fine, asking them without thinking first isn't in my opinion. – Dirk Feb 25 '14 at 12:36
  • @Dirk I guess. At least OP accepted an answer :) That's a good thing. – Alex Feb 25 '14 at 12:56
  • when I typed "How to print a backslash (\) at the beginning of a string (c#)" I did not find an answer under: "Questions that may already have your answer" so I asked it. – kimliv Feb 25 '14 at 13:48

3 Answers3

12

\ is an escape sequence character.

Escape Sequence -- Represents

             \\ -- Backslash

If you want to use it in your string, you should escape it with another \ character.

string test = "\\test.xml";

or your can use verbatim string literal with @ character like;

string test = @"\test.xml";
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • 1
    +1 I prefer the @"..." personally because it makes the text a lot more readable and gets rid of all the ugly escapes. – Alex Feb 25 '14 at 12:05
  • @Alex: it also allows to leave a multi-line string as it is which is handy especially for sql queries. – Tim Schmelter Feb 25 '14 at 12:07
  • Yes, actually `'\t'` is _one_ character, a [TAB](http://en.wikipedia.org/wiki/Tab_key#Tab_characters). Each of `'e'`, `'s'`, `'t'`, `'.'`, `'x'`, `'m'`, `'l'` is also one character, so the string from the question had length `8`, not `9`. – Jeppe Stig Nielsen Feb 25 '14 at 12:07
4

Just add escape sequence as:

string test = "\\test.xml";

Better option is to prepend '@' to avoid all escape sequences from string as:

string test = @"\test.xml";
M.S.
  • 4,283
  • 1
  • 19
  • 42
1
string test = @"\test.xml";

or

string test = "\\test.xml";
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
ali asadi
  • 11
  • 1