I am trying to format a text so I can provide a template some RFT text.
My string is declared with the stringformater as:
var fullTitleString = string.Format(
CultureInfo.CurrentCulture,
"{{\\Test",
title,
filterName);
But I keep obtaining a string as "{\Test". Using a single backslash results on errors at it does not understand the \T escaped character.
Doing #"{{\Test" also yields "{\Test". I have looked over the MSDN documentation and other questions where they tell to use another backslash as escaping character, but it doesn't seem to work.
There are two levevls of escaping here:
1. Escaping string literals
In c# strings, a backslash (\) is used as special character and needs to be escaped by another \. So if your resulting string should look like \\uncpath\folder your string literal should be var s = "\\\\uncpath\\folder".
2. Escape format strings
string.Format uses curly braces for place holders, so you need to escape them with extra braces.
So let's say you have
string title = "myTitle";
string filterName = "filter";
then
string.Format("{{\\Test {0}, {1}}}", title, filterName);
results in
{\Test myTitle, filter}
If you want two curly braces at the beginning, you need to put four in your format string:
string.Format("{{{{\\Test {0}, {1}}}", title, filterName);
results in
{{\Test myTitle, filter}
If you provide a clear example of what you are trying to achieve, I may tell you the correct format string.
Side note: In C# 6 the last example could also be $"{{{{\\Test {title}, {filterName}}}" (using string interpolation without explicitly calling string.Format)
NOTE: The Visual Studio debugger always shows the unescaped string literal. So if you declare a string like string s = "\\" you will see both backslashes in your debugger windows, but if you Console.WriteLine(s) only one backslash will be written to console.
Related
Perhaps I didn't see or understand any of the answers I read but I am having trouble using verbatim string literal (#) with settings.Default.(mysetting). I am trying to do something like
Directory.GetFiles(#Setting.Default.(mysetting),"*.txt");
and cant seem to find the right syntax to make this work.
The # identifies a string constant literal where back slashes should not be interpreted as escape signs. You can not use it in front of method invocations as you attempt here.
A valid assignment might be
string path = #"c:\temp\example.txt";
Usually a \t would be interpreted as a tabulation character thus making the file reference illegal. It is exactly identical to
string path = "c:\\temp\\example.txt" ;
But bit easier to read.
# verbatim string is used with string literals. So your code should be:
Directory.GetFiles(Setting.Default.(mysetting),#"*.txt");
because "*.txt" is the string literal in your code.
(Although not related, but you can use # with variable names see C# Variable Naming and the # Symbol)
To use # as part of a verbatim string literal, the string literal must be right there - not just a property, method, etc. that returns a string.
string myStr = #"I'm verbatim, I contain a literal \n";
string myStr2 = "I'm not\nI have a newline";
string myStr3 = #myStr2; // still contains a newline, not a literal "\n"
Using # in front of an identifier allows you to use reserved keywords as identifiers. For example:
string #if = "hello!"; // valid
It also works on non-reserved words, where it has no real effect.
string #myVar = "hello!"; // valid
string newVar = myVar; // can be referred to either way
Unless I'm missing it, you still need to wrap the string within quotation marks.
So in microsoft visual studio I have a string that is compiled into a regex. My string is "#(\d+(.\d+)?)=(\d+(.\d+)?)". I cannot compile my program because I get an error saying that \d is a unrecognized escape character. How do I tell it to shut up and let me regex like a pro?
Begin your string with #, that causes the compiler to leave (almost) all characters alone, unescaped (the exception is ", which can be escaped as ""):
#"#(\d+(.\d+)?)=(\d+(.\d+)?"
The problem is that c# does not like the \d inside the string. Use a verbatim string instead
string pattern = #"#(\d+(.\d+)?)=(\d+(.\d+)?)";
The "#" denotes it. C# will not look for escape sequences in the string. If you have to escape a " use two "".
Of cause you can use normal strings. but then you will have to escape the backslashes
string pattern = "#(\\d+(.\\d+)?)=(\\d+(.\\d+)?)";
If you're using a normal string, you need to escape your backslashes, like so:
"#(\\d+(.\\d+)?)=(\\d+(.\\d+)?)"
Basically, you're putting a literal string into C#; the C# compiler sees the string first, and tries to interpret \d as an escape sequence (which doesn't exist, hence error). Therefore, you use \\d to get the C# compiler to see the string as \d, which then gets passed to the regex engine (which does recognize \d as something meaningful). (yes, if you want to match a literal backslash in your regex pattern, you need to use \\\\)
But in C#, you have the alternative of just prepending the string with # to get the compiler to leave the string alone (though " still needs escaping), so that would be like this:
#"#(\d+(.\d+)?)=(\d+(.\d+)?)"
You could also use a verbatim string literal (I prefer to use these because of readability).
Use #"(#\d+(.\d+)?)=(\d+(.\d+)?)"
The #" sign indicates that the string shouldn't interpret escaped characters (A character prefixed by a \) until the closing " is reached.
Note: You can match a single " in your search pattern by double quoting instead "". For instance you can match "Hello" by using the pattern #"""\w+"""
I have a StringBuilder object and wanted to used its Append() method to add this whole string to it:
so I used "#" and copy pasted that whole string like this, but it gives a lot of errors such as "; expected ", "Invalid Expression '<'" , etc
myString.Append(#"COPY-PASTED-THAT_WHOLE-STRING");
What is the correct way of adding this string to my string builder object?
Thank you.
Even with an # prefixing the string, you need to escape any " characters, otherwise they will be interpreted as the end of the string literal.
EDIT:
e.g.
var entity = #"<!ENTITY xsd ""http://www.w3.org/2001/XMLSchema#"">";
Double-quotes (") inside the string you want to paste need to be escaped by being replaced with two consecutive double-quotes, as in "". Here's a trick to use:
Paste your string into a new instance of Notepad
Replace all double quotes (") with two double quotes ("")
Select and copy the content from Notepad back into clipboard
Paste it into #"…" in your code/text editor
From C# docs:
In a verbatim string literal, the characters between the delimiters
are interpreted verbatim, the only exception being a
quote-escape-sequence.
You can use the # syntax to add multiple lines. But you need to escape the "s inside your string by using ""
For example
#"<Ontology xmlns=""http://www.w3.org/2002/07/owl#"""
If you don't escape them, C# will treat the quote mark as the end of the string.
One option, as others have said, is to escape all of the double quotes (") with a double double quote ("").
What I prefer to do, as it makes the code more readable, when adding an XML block as a literal string, is to use single quotes rather than double quotes. Just put the XML file into a text editor and do a replace all on double quote with a single quote (').
Another option, since your XML literal isn't all that short, is to put it into a file and read in that file at runtime.
You can escape them like this as well...
#"<Ontology xmlns=\"http://www.w3.org/2002/07/owl#\""
I read some C# article to combine a path using Path.Combine(part1,part2).
It uses the following:
string part1 = #"c:\temp";
string part2 = #"assembly.txt";
May I know what is the use of # in part1 and part2?
# is not related to any method.
It means that you don't need to escape special characters in the string following to the symbol:
#"c:\temp"
is equal to
"c:\\temp"
Such string is called 'verbatim' or #-quoted. See MSDN.
As other have said its one way so that you don't need to escape special characters and very useful in specifying file paths.
string s1 =#"C:\MyFolder\Blue.jpg";
One more usage is when you have large strings and want it to be displayed across multiple lines rather than a long one.
string s2 =#"This could be very large string something like a Select query
which you would want to be shown spanning across multiple lines
rather than scrolling to the right and see what it all reads up";
As stated in C# Language Specification 4.0:
2.4.4.5 String literals
C# supports two forms of string
literals: regular string literals and
verbatim string literals. A regular
string literal consists of zero or
more characters enclosed in double
quotes, as in "hello", and may include
both simple escape sequences (such as
\t for the tab character), and
hexadecimal and Unicode escape
sequences. A verbatim string literal
consists of an # character followed by
a double-quote character, zero or more
characters, and a closing double-quote
character. A simple example is
#"hello". In a verbatim string
literal, the characters between the
delimiters are interpreted verbatim,
the only exception being a
quote-escape-sequence. In particular,
simple escape sequences, and
hexadecimal and Unicode escape
sequences are not processed in
verbatim string literals.
It denotes a verbatim string literal, and allows you to use certain characters that normally have special meaning, for example \, which is normally an escape character, and new lines. For this reason it's very useful when dealing with Windows paths.
Without using #, the first line of your example would have to be:
string part1 = "c:\\temp";
More information here.
With # you dont have to escape special characters.
So you would have to write "c:\\temp" without #
If more presise it is called 'verbatim' strings. You could read here about it:
http://msdn.microsoft.com/en-us/library/aa691090(v=vs.71).aspx
The # just indicates a different way of specifying a string such that you do not have to escape characters with . the only caveat is that double quotes need to be "" to represent a single ".
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to use “\” in a string without making it an escape sequence - C#?
Why is it giving me an error in C# when I use a string like: "\themes\default\layout.png"? At the "d" and "l" location? It says unrecognized escape sequence. And how do I stop it from giving me an error when I use: "\"?
Thans
You need to escape it with an additional \:
string value = "\\themes\\default\\layout.png";
or use the # symbol:
string value = #"\themes\default\layout.png";
which will avoid you from doubling all \.
Or if you are dealing with paths (which is what it seems you are) you could use the Path.Combine method:
string value = Path.Combine(#"\", "themes", "default", "layout.jpg");
You're using a backslash to escape 't' and 'd'. If you want to escape the actual backslash you need to do so:
"\\themes\\default\\layout.png"
"Regular" string literals treat the \ character as a special character, used for escape sequences to insert quickly special characters in strings - \n, for example, is used to insert the newline character, \" is used to insert the " character without terminating the string, and so on.
Because of this, to insert a backslash into a "normal" string you have to insert the corresponding escape sequence, which, unsurprisingly, is \\; you would then write in your case:
"\\themes\\default\\layout.png"
Failing to escape the backslashes will result in weird results or errors like the ones you got, since the compiler will try to interpret the couple backslash-letter that follows it as an escape sequence; if such sequence is defined you'll get unwanted characters (e.g. the first \t is escaped to a tab character), if it's not (like \l) you'll get an error about an undefined escape sequence.
Another option, if you don't need to escape any character, is to use the so-called "verbatim" strings literals: if you prefix the string with an # character the escape sequences will be disabled, and the string you write will be taken verbatim by the compiler. The only exception to this rule is for quotes, that can be inserted inside the verbatim string via the "quote escape sequence", i.e. "". In your case you would write:
#"\themes\default\layout.png"
For more info about regular vs verbatim string literals have a look at their documentation.
The backslash is treated as an escape character. Either escape the backslash itslef in the string like so:
"\\themes\\default\\layout.png"
or disable escaping altogether using a verbatim string literal:
#"\themes\default\layout.png"