Using "#" to insert multiple lines of strings in StringBuilder - c#

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#\""

Related

Proccess.Start can not find the path with \\ in c# winforms

I am trying to open a pdf file that is located on the network :
I call the file like this in c# (Sorry for sending my code as a picture because of breakpoint i have to)
But it can't find the path .Another thing that i should add is when i call the file outside the c# like this \\127.0.0.1\dccfile\test\dcc1\1.pdf it works .
The value you're looking at in the debugger tooltip is a C# literal, not a string. C# literals delimit strings with straight quotes " and escapes metacharacters with backslashes \. See the quotes at the start and end of the literal in the tooltip? They're not part of the string. Backslashes are C# metacharacters, to include one in a string you have to precede it with another backslash. The C# literal "\\" encodes a string containing a single backslash character. The first \ you see in "\\127.0.0... is a metacharacter telling C# that the next character is a literal backslash, not a metacharacter. The code "\\127.0.0.1\\DCCFile\\test\\dcc1\\1.pdf" you see in the tooltip encodes the C# string \127.0.0.1\DCCFile\test\dcc1\1.pdf with no quotes and single backslashes.
Your problem is the value of Configuration.AccountDetail.DCCFileAddress needs to start with two backslashes and it does not.
Your code pathString.Replace(#"\\", #"\") will have no effect because there are no double backslashes in your string; the debugger is displaying the backslashes doubled so you know they are literal backslashes and not metacharacters.

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.

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

C#, escape double quote not working as expected

I'm trying to escape quotes in an xpath string like so:
var mktCapNode = htmlDoc.DocumentNode.SelectSingleNode("//*[#id=""yfs_j10_a""]");
The actual string I want passed is:
//*[#id="yfs_j10_a"]
This gives a compiler errors: ) expected and ; expected
I'm sure it's simple but I'm stumped. Any ideas?
You need to make this a verbatim string to use the "" as an escape
#"//*[#id=""yfs_j10_a""]"
For a normal string literal you need to use backslashes to escape the double quotes
"//*[#id=\"yfs_j10_a\"]"
Or use the escape char '\':
"//*[#id=\"yfs_j10_a\"]"
In C# the \ character is used to escape (see documentation).
This is different from VB where there are no escape characters except "" which escapes to ".
This means in C# you do not need vbCrLf to start a new line or vbTab to add a tab character to a string. Instead use "\r\n" and "\t".
You can also make the string a literal using the # character, but I do not think this works with the quotation mark.
Add the # prefix to your string.
#"//*[#id=""yfs_j10_a""]"
or escape the quotes with a \
"//*[#id=\"yfs_j10_a\"]"

C# string - creating an unescaped backslash

I am using .NET (C#) code to write to a database that interfaces with a Perl application. When a single quote appears in a string, I need to "escape" it. IOW, the name O'Bannon should convert to O\'Bannon for the database UPDATE. However, all efforts at string manipulation (e.g. .Replace) generate an escape character for the backslash and I end up with O\\'Bannon.
I know it is actually generating the second backslash, because I can read the resulting database field's value (i.e. it is not just the IDE debug value for the string).
How can I get just the single backslash in the output string?
R
Well I did
"O'Bannon".Replace("'","\\'")
and result is
"O\'Bannon"
Is this what you want?
You can use "\\", which is the escape char followed by a backslash.
See the list of Escape Sequences here: http://msdn.microsoft.com/en-us/library/h21280bw.aspx
even better assign a var to the replace so that you can check it as well if needed
var RepName = "O'Bannon";
var Repstr = RepName.Replace("'","\\'");
You can also use a verbatim string
s = s.Replace("'", #"\'");

Categories