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("\\"," ");
Related
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".
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.
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("'", "''");
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 ":
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.