C# Settings with verbatim string literal - c#

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.

Related

On C# escape curly braces and a backslash after

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.

Properly escape filepaths

How do I escape with the #-sign when using variables?
File.Delete(#"c:\test"); // WORKS!
File.Delete(#path); // doesn't work :(
File.Delete(#"c:\test"+path); // WORKS
Anyone have any idea? It's the 2nd example I want to use!
Strings prefixed with # character are called verbatim string literals (whose contents do not need to be escaped).
Therefore, you can only use # with string literals, not string variables.
So, just File.Delete(path); will do, after you assign the path in advance of course (from a verbatim string or some other string).
Verbatim strings are just a syntactic nicety to be able to type strings containing backslashes (paths, regexes) easier. The declarations
string path = "C:\\test";
string path = #"C:\test";
are completely identical in their result. Both result in a string containing C:\test. Note that either option is just needed because the C# language treats \ in strings as special.
The # is not some magic pixie dust needed to make paths work properly, it has a defined meaning when prefixed to strings, in that the strings are interpreted without the usual \ escape sequences.
The reason your second example doesn't work like you expect is that # prefixed to a variable name does something different: It allows you to use reserved keywords as identifiers, so that you could use #class as an identifier, for example. For identifiers that don't clash with keywords the result is the same as without.
If you have a string variable containing a path, then you can usually assume that there is no escaping needed at all. After all it already is in a string. The things I mentioned above are needed to get text from source code correctly through the compiler into a string at runtime, because the compiler has different ideas. The string itself is just data that's always represented the same.
This still means that you have to initialise the string in a way that backslashes survive. If you read it from somewhere no special treatment should be necessary, if you have it as a constant string somewhere else in the code, then again, one of the options at the top has to be used.
string path = #"c:\test";
File.Delete(path);
This will work only on a string. The "real" string is "c:\\test".
Read more here.
There's a major problem with your understanding of the # indicator.
#"whatever string" is a literal string specifier verbatim string literal. What it does is tells the C# compiler to not look for escape sequences. Normally, "\" is an escape sequence in a string, and you can do things like "\n" to indicate a new line or "\t" to indicate a tab. However, if you have #"\n", it tells the compiler "no, I really want to treat the backslash as a backslash character, not an escape sequence."
If you don't like literal mode, the way to do it is to use "\\" anywhere you want a single backslash, because the compiler knows to treat an escaped backslash as the single character.
In either case, #"\n" and "\\n" will produce a 2-character string in memory, with the characters '\' and 'n'. It doesn't matter which way you get there; both are ways of telling the compiler you want those two characters.
In light of this, #path makes no sense, because you don't have any literal characters - just a variable. By the time you have the variable, you already have the characters you want in memory. It does compile ok, as explained by Joey, but it's not logically what you're looking for.
If you're looking for a way to get rid of occurrences of \\ within a variable, you simply want String.Replace:
string ugly = #"C:\\foo";
ugly = ugly.Replace(#"\\", #"\");
First and third are actual paths hence would work.
Second would not even compile and would work if
string path = #"c:\test";
File.Delete(path);

Why assign a string with #? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What's the # in front of a string in C#?
This is something I have questioned for a long time but never bothered to figure out. When I download third party libraries I have often seen string assignments using a # symbol before the string.
string myString = #"Some text";
But there seems to be absolutely no difference if I simply do
string myString = "Some text";
So what is the # doing?
It is signifies a verbatim string literal and allows you to not have to escape certain characters:
string foo = #"c:\some\path\filename.exe";
vs:
string foo = "c:\\some\\path\\filename.exe";
string reason = #"this string literal mea\ns something different with an # in front than without";
Without the #, the above string would have a new-line character instead of an 'n' in the word "means". With the #, the word "means" looks just like you see it. This feature is especially useful for things like file paths:
string path = #"C:\Users\LookMa\NoDoubleSlashes.txt";
It is a verbatim string literal. It lets you do things like #"C:\" instead of "C:\\", and is especially useful in regex and file paths, since these often use backslashes that shouldn't be parsed by the compiler. See the documentation for more info.
In this case there is no difference.
All '#' does is allow you to omit escape backslashes. If you use '#' and want in include double quotes in the string you need to double up the double quotes.

What is the significance of the # symbol in C sharp? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What's the # in front of a string for .NET?
I understand using the # symbol is like an escape character for a string.
However, I have the following line as a path to store a file to a mapped network drive:
String location = #"\\192.168.2.10\datastore\\" + id + "\\";
The above works fine but now I would like to get a string from the command line so I have done this:
String location = #args[0] + id + "\\";
The above doesn't work and it seems my slashes aren't ignored. This my command:
MyProgram.exe "\\192.168.2.10\datastore\\"
How can I get the effect of the # symbol back?
It is used for two things:
create "verbatim" strings (ignores the escape character): string path = #"C:\Windows"
escape language keywords to use them as identifiers: string #class = "foo"
In your case you need to do this:
String location = args[0] + id + #"\\";
The # symbol in front of a string literal tells the compiler to ignore and escape sequences in the string (ie things that begin with a slash) and just to create the string "as-is"
It can also be used to create variables whose name is a reserved work. For example:
int #class=10;
If you don't prefix the # then you'd get a compile-time error.
You can also prefix it to variables that are not reserved word:
int #foo=22;
Note that you can refer to the variable as foo or #foo in your code.
The # prefix means the string is a literal string and the processing of escape characters is not performed by the compiler, so:
#"\n"
is not translated to a newline character. Without it, you'd have:
String location = "\\\\192.168.2.10\\datastore\\\\" + id + "\\\\";
which looks a bit messy. The '#' tidies things up a bit. The '#' can only be prefixed to string constants, that is, things inside a pair of double quotes ("). Since it is a compiler directive it is only applied at compile time so the string must be known at compile time, hence,
#some_string_var
doesn't work the way you think. However, since all the '#' does is stop processing of escaped characters by the compiler, a string in a variable already has the escaped character values in it (10,13 for '\n', etc). If you want to convert a '\n' to 10,13 for example at run time you'll need to parse it yourself doing the required substitutions (but I'm sure someone knows a better way).
To get what you want, do:
String location = args[0] + id + "\\";
The # symbol has two uses in C#.
To use a quotes instead of escaping. "\windows" can be represented as #"\windows". "\"John!\"" can be represented #"""John!""".
To escape variable names (for example to use a keyword as a parameter name)
private static void InsertSafe (string item, object #lock)
{
lock (#lock)
{
mylist.Insert(0,item);
}
}
#-quoted string literals start with # and are enclosed in double quotation marks. For example:
#"good morning" // a string literal
The advantage of #-quoting is that escape sequences are not processed, which makes it easy to write, for example, a fully qualified file name:
#"c:\Docs\Source\a.txt" // rather than "c:\\Docs\\Source\\a.txt"
To include a double quotation mark in an #-quoted string, double it:
#"""Ahoy!"" cried the captain." // "Ahoy!" cried the captain.
Another use of the # symbol is to use referenced (/reference) identifiers that happen to be C# keywords. For more information, see 2.4.2 Identifiers.
http://msdn.microsoft.com/en-us/library/362314fe(v=vs.71).aspx
In this case you may not need to use #; just make it
String location = args[0] + id + "\\";
The # symbol is only relevant for string literals in code. Variables should never modify the contents of a string.
The # symbol goes right before the quotes. It only works on string literals, and it simply changes the way the string is understood by the compiler. The main thing it does is cause \ to be interpreted as a literal backslash, rather than escaping the next character. So you want:
String location = args[0] + id + #"\\";
By default the '\' character is an escape character for strings in C#. That means that if you want to have a backslash in your string you need two slashes the first to escape the second as follows:
string escaped = "This is a backslash \\";
//The value of escaped is - This is a backslash \
An easier example to follow is with the use of quotes:
string escaped = "To put a \" in a string you need to escape it";
//The value of escaped is - To put a " in a string you need to escape it
The # symbol is the equivalent of "ignore all escape characters in this string" and declare it verbatim. Without it your first declaration would look like this:
"\\\\192.168.2.10\\datastore\\\\" + id + "\\";
Note that you already didn't have the # on your second string, so that string hasn't changed and still only contains a single backslash.
You only need to use the # symbol when you are declaring strings. Since your argument is already declared it is not needed. So your new line can be:
String location = args[0] + id + "\\";
or
String location = args[0] + id + #"\";
If you load from the command line, it will already be escaped for you. This is why your escapes are "ignored" from your perspective. Note that the same is true when you load from config, so don't do this:
<add key="pathToFile" value="C:\\myDirectory\\myFile.txt"/>
If you do, you end up with double strings, as ".NET" is smart enough to escape thins for you when you load them in this manner.

Using the literal '#' with a string variable

I have a helper class pulling a string from an XML file. That string is a file path (so it has backslashes in it). I need to use that string as it is... How can I use it like I would with the literal command?
Instead of this:
string filePath = #"C:\somepath\file.txt";
I want to do this:
string filePath = #helper.getFilePath(); //getFilePath returns a string
This isn't how I am actually using it; it is just to make what I mean a little clearer. Is there some sort of .ToLiteral() or something?
I don't think you have to worry about it if you already have the value. The # operator is for when you're specifying the string (like in your first code snippet).
What are you attempting to do with the path string that isn't working?
I'm not sure if I understand. In your example: if helper.getFilePath() returns "c:\somepath\file.txt", there will be no problem, since the # is only needed if you are explicitely specifying a string with "".
When Functions talk to each other, you will always get the literal path. If the XML contains c:\somepath\file.txt and your function returns c:\somepath\file.txt, then string filePath will also contain c:\somepath\file.txt as a valid path.
The #"" just makes it easier to write string literals.
string (C# Reference, MSDN)
Verbatim string literals start with # and are also enclosed in double quotation marks. For example:
#"good morning" // a string literal
The advantage of verbatim strings is that escape sequences are not processed, which makes it easy to write, for example, a fully qualified file name:
#"c:\Docs\Source\a.txt" // rather than "c:\\Docs\\Source\\a.txt"
One place where I've used it is in a regex pattern:
string pattern = #"\b[DdFf][0-9]+\b";
If you have a string in a variable, you do not need to make a "literal" out of it, since if it is well formed, it already has the correct contents.
In C# the # symbol combined with doubles quotes allows you to write escaped strings. E.g.
print(#"c:\mydir\dont\have\to\escape\backslashes\etc");
If you dont use it then you need to use the escape character in your strings.
http://msdn.microsoft.com/en-us/library/aa691090(VS.71).aspx
You dont need to specify it anywhere else in code. In fact doing so should cause a compiler error.
You've got it backwards. The #-operator is for turning literals into strings, while keeping all funky characters. Your path is already a string - you don't need to do anything at all to it. Just lose the #.
string filePath = helper.getFilePath();
The string returned from your helper class is not a literal string so you don't need to use the '#' character to remove the behaviour of the backslashes.

Categories