Concatenate string literals with DirectoryInfo enumeration and adding quotation marks. - c#

This seems like such an obscure question, but here it goes:
Is there a way to concatenate String Literals with a DirectoryInfo enumeration (which contains a file path) while adding quotations around the file path? Further, how can I prevent backslashes from being doubled when converting a DirectoryInfo enumeration to a string? My situation is as follows:
DirectoryInfo filePathDirectory = new DirectoryInfo(filePath);
Process a = new Process();
a.StartInfo.FileName = "C:\\Windows\\system32\\lpr.exe";
a.StartInfo.Arguments = "-SServername.Domain.net -Plp " + "\"" + filePathDirectory + "\"";
a.StartInfo.UseShellExecute = false;
a.Start();
a.WaitForExit();
filePathDirectory starts with a value of:
{\\ServerName\Share\Folder\Folder\FileName.xls}
Which I think is converted into a string once concatenated into a.StartInfo.Arguments which is assigned the value of:
-SServername.Domain.net -Plp \"\\\\ServerName\\Share\\Folder\\Folder\\FileName.xls\"
This is bad because, the number of backslashes in the path doubled. How can I ensure no backslashes are added to the path?
On top of that, to add a quotation marks, I've used the backslash escape sequence; But the backslash from this escape sequence is inadvertently added to my string. How can I add quotation marks around the file path which is contained in a.StartInfo.Arguments?
P.S. I hope this makes sense, please ask questions if you need clarification.

The backslashes are not doubled and the backslash of the quotes also "isn't there". You can verify it by Console.WriteLine(a.StartInfo.Arguments) or MessageBox.Show(a.StartInfo.Arguments).
What you are seeing - in the debugger I assume - is the representation of the string with the escape characters not translated - just as you would need to enter it in the IDE.
Example:
string s = "\"";
This will show in the debugger as "\"" but it will display on screen as ":

Related

string replacement not replacing all instances

Using C# in Visual Studio 13 - I'm trying to replace some slashes in my string using the replace command. The VS tool tip tells me, "Returns a new string in which all occurrences of a specified Unicode character in this instance are replaced with another specified Unicode character"
My string, which is passed in as a parameter is:
path = "\\\\ServerName\\Folder1\\Folder2"
I create a new string:
string newPath = path.Replace(#"\\", #"//");
According to the tool tip it should replace all instances of \\ with //, but instead my resulting string is:
"//\\ServerName\\Folder1\\Folder2"
What am I doing wrong? It seemed pretty straight forward to me, or so I thought.
What I'm trying to get is:
"////ServerName//Folder1//Folder2"
Your output will be //ServerName\Folder2\Folder2, as there is only one actual occurrence of two backslashes, namely at the beginning of \\ServerName.
When inspecting a string's value, the debugger shows a single backslash (\) as two (\\), but when replacing, you want to replace one:
string newPath = path.Replace(#"\", #"/");
Note that you don't need to escape a slash character (/).
Try this:
string newPath = path.Replace("\\", "/");
Your path string really is: #"\\ServerName\Folder1\Folder2".

Remove backslash from json string in wp8

I have converted an object into string in wp8,by using
string str=JSONConvert.SerializeObject(object);
Now I am getting a string like this:-
{\"catGroup\":[{\"category\":{\"cgsId\":9,\"cgsName\":\"Ignition & Engine Filters\",\"values\":null}..
I want to remove the backslash from the string.I have used
str = str.Replace(#"\","");
But still I am getting the string containing backslashes.
How to remove this?
Those backslashes you see in your debug are not actually there. They are used as a escape character.
In c# the " indicates that you are talking about a string value. If you want a string to contain the " character you will have to type \" else you will close the string. If you don't know what I mean just try this
string wrong = "type a " in your string";
string correct = "type a \" in your string";
Since the debugger is working in the same way as your code compiler it has to add the \ to display a " character. Seeing your comments you want do write the string to a database, you can just do that straight away without worrying about the backslashes.
try this
str.replaceall("\\"," ");

How do I write a backslash (\) in a string?

I want to write something like this C:\Users\UserName\Documents\Tasks in a textbox:
txtPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)+"\Tasks";
I get the error:
Unrecognized escape sequence.
How do I write a backslash in a string?
The backslash ("\") character is a special escape character used to indicate other special characters such as new lines (\n), tabs (\t), or quotation marks (\").
If you want to include a backslash character itself, you need two backslashes or use the # verbatim string:
var s = "\\Tasks";
// or
var s = #"\Tasks";
Read the MSDN documentation/C# Specification which discusses the characters that are escaped using the backslash character and the use of the verbatim string literal.
Generally speaking, most C# .NET developers tend to favour using the # verbatim strings when building file/folder paths since it saves them from having to write double backslashes all the time and they can directly copy/paste the path, so I would suggest that you get in the habit of doing the same.
That all said, in this case, I would actually recommend you use the Path.Combine utility method as in #lordkain's answer as then you don't need to worry about whether backslashes are already included in the paths and accidentally doubling-up the slashes or omitting them altogether when combining parts of paths.
To escape the backslash, simply use 2 of them, like this:
\\
If you need to escape other things, this may be helpful..
There is a special function made for this Path.Combine()
var folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var fullpath = path.Combine(folder,"Tasks");
Just escape the "\" by using + "\\Tasks" or use a verbatim string like #"\Tasks"
txtPath.Text = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)+"\\\Tasks";
Put a double backslash instead of a single backslash...
even though this post is quite old I tried something that worked for my case .
I wanted to create a string variable with the value below:
21541_12_1_13\":null
so my approach was like that:
build the string using verbatim
string substring = #"21541_12_1_13\"":null";
and then remove the unwanted backslashes using Remove function
string newsubstring = substring.Remove(13, 1);
Hope that helps.
Cheers

New Line in Constant error when trying to insert escape character in string

I am writing some C# code in which I am fetching values from the database and using it. The problem I am facing is as below.
If my fetched value from the database is:
string cat1 = "sotheby's";
Now while using cat1 I want to insert an escape character before the single quote. To achieve this I have written the below code:
string cat1 = "sotheby's";
if (cat1.Contains("'")) {
var indexofquote = cat1.IndexOf("'");
cat1.Insert(indexofquote-1,"\");
var cat2 = cat1;
}
The error arises on the insert line with the backslash (escape character). The error is New Line in Constant.
Please help me correct this error.
You can't just write "\" in C# code. That will produce the "New Line in Constant" error because it 'escapes' the second quote so that it doesn't count. And the string isn't closed.
Use either "\\" (escaping the \ with itself)
or use #"\" (a verbatim string).
The Backslash in string literals is an escape character, so it must either be escaped itself:
"\\"
Or you can use a so-called verbatim string literal:
#"\"
See: http://msdn.microsoft.com/en-us/library/aa691090.aspx
Regarding your compile error: The backslash escapes the following quotation mark, thus the string literal is not recognized as closed. The following characters ) and ; are valid for string literals, however the line ending (newline) is not. Hence the error.
That will only replace 1 single quote.
To get them all use:
string cat1_escaped = cat1.Replace("'", "\'");
Although a lot of databases don't escape quotes like that, but rather by doubling them:
string cat1_escaped = cat1.Replace("'", "''");

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.

Categories