Losing quotes or getting extra \ sign arround string - c#

Here is something pretty basic for c# String class.
//I get string error as input parameter
string error = "Hello World!";
string eventHandlerStr = "onmouseover = 'ShowError(" + "event" + ", \"" + error + "\")'";
// result is "onmouseover = 'ShowError(event, \"Hello World!"\)'"
How to get result without \ around "Hello World!"? And I need quotes arround Hello World!
If I do this:
string eventHandlerStr = "onmouseover = 'ShowError(" + "event" + ", " + error + ")'";
I get Hello World! without quotes.
I tried even removing \ character with String.Remove method but \ stayed there after removing.

Try verbatim string -> #
Here you are everything you need:
https://msdn.microsoft.com/en-us/library/aa691090(v=vs.71).aspx
UPDATE 2018/06/07
New documentation from MS:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/verbatim (second point)
Cache from WebArchive for original link: https://web.archive.org/web/20170730011023/https://msdn.microsoft.com/en-us/library/aa691090(v=vs.71).aspx

Can you try this?
string format = #"onmouseover = 'ShowError(event, ""{0}"")'";
string error = "HelloWorld";
string pqr = string.Format(format, error);

Related

C# double " mark in textstring

hi guys I made an app to extract .lua file when I push the button
my problem is I need to pass this string like this
QUESTID = LuaGetQuestID("QNO_QUEST_AR")
QNO_QUEST_AR extracted from textBox1 so my code =
File.Write(" QUESTID = LuaGetQuestID("+textBox1.Text+")\r\n");
I need to add 2x " mark like this (""+textBox1.Text+"")
anyway to do that ? thanks
You can use a 'verbatim identifier' (#) and escape quotes with double quotes.
Note that you can also combine the 'string interpolation identifier' ($) so that you're not building up the string with pluses. See:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/verbatim
and
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
Then you could write your code something like:
var myString = #$"QUESTID = LuaGetQuestID(""{textBox1.Text}"")";
thanks, guys it works with this code
File.Write(" QUESTID = LuaGetQuestID(" + '"' + textBox1.Text + '"' + ")\r\n");

How do I use an illegal character?

public void CreateCertificate()
{
File.Create($"
{#"C:\Users\Director\Documents\TestCertApp\TestSub\" + thisYear +
" Certificates- " + certType + "\""}{myFileName}.ppt", 1 ,
FileOptions.None);
}
So I need the backslash between certype and filename to show it belongs within the folder and not next to. It says its an illegal character but how would I get the file in the folder without it?
Based on the code that you wrote the file path that will be generated is (based on my own substitutions for the variables):
String thisYear = "2019";
String certType = "UnderGrad";
String myFileName = "myfile";
String fileToCreate = $"{#"C:\Users\Director\Documents\TestCertApp\TestSub\" + thisYear + " Certificates- " + certType + "\""}{myFileName}.ppt";
Debug.Print(fileToCreate);
Will give you this output:
C:\Users\Director\Documents\TestCertApp\TestSub\2019 Certificates- UnderGrad"myfile.ppt
If you notice there is a " before the filename part of myfile.ppt - This is where the Illegal Character comes from.
If you use this code fragment to generate the path:
String basePath = #"C:\Users\Director\Documents\TestCertApp\TestSub\";
String certificateFolder = $"{thisYear} Certificates- {certType}";
String correctFilePath = Path.Combine(basePath, certificateFolder, $"{myFileName}.ppt");
Debug.Print(correctFilePath);
This will result in the output of:
C:\Users\Director\Documents\TestCertApp\TestSub\2019 Certificates- UnderGrad\myfile.ppt
This version has a \ where the previous code had a " and is no longer illegal, but conforms to the requirement that you wrote the files being in the folder.
Something else to note:
You may want to use Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); to get the path to the MyDocuments folder of the user.
Well, the short answer is that you cannot use an illegal character in a path or file name. Otherwise it wouldn't be illegal. :)
But it seems that the problem here is that you though you were adding a backslash (\) character, when really you were adding a double quote (") character. So if everything else is ok, you can just replace "\"" with "\\" and it should work.
Part of the problem is also that you're doing some strange combination of string interpolation, and it makes the code really hard to read.
Instead you can use just string interpolation to simplify your string (I had to use concatenation below to prevent horizontal scrolling, but you could remove it):
string filePath = $#"C:\Users\Director\Documents\TestCertApp\TestSub\{thisYear} " +
$#"Certificates- {certType}\{myFileName}.ppt";
But even better would be to use the Path.Combine method, along with some variables, to make the intent very clear:
var rootDir = #"C:\Users\Director\Documents\TestCertApp\TestSub"
var fileDir = $"{thisYear} Certificates- {certType}"
var fileName = "{myFileName}.ppt";
var filePath = Path.Combine(rootDir, fileDir, fileName);

Issue with string in c#?

I am creating a string in c#.
string jsVersion = #"function getContent() {
var content = " + "\"" + documentString + "\"" + #"
return content;
}";
The documentString variable contains a huge string which have line breaks also. Now in javascript when i load this string the content variable does not contains a valid string (because of line breaks).
Now how can i create a string which is valid even if there is line breaks ?
You can use HttpUtility.JavaScriptStringEncode
Can you use string.format instead of concatenation in this fashion?
An example:
string jsVersion = string.format("function getContent() {var content = '{0}'return content; }",documentString);
This will replace your line breaks with <br/>:-
stringToDecode.replace(/\n/, '<br />')
If you want to get rid of the line breaks just remove # from the sting.
# acts a verbatim for your string and therefor adds the line breaks you entered with your declaration.
string jsVersion = "function getContent() {
var content = " + "\"" + documentString + "\"" + "
return content;
}";
should do the trick.

Ignore characters "" in string

I want to have a program that will be able to write to the file:
addr_new = serverInfo.REGION_DICT[0][serverNum]["channel"][serverChannel]["ip"]
, but must ignore the characters "" in the text
My restult: Visual studio does not ignores characters "" in string and wants strings like IP etc.. thx for help
Sry for my english
There is my Program:
string path = System.IO.Directory.GetCurrentDirectory()+ "logininfo.py";
string[] lines = {
"import serverInfo"
, "serverNum=1"
, "serverChannel=1"
, "addr_new = serverInfo.REGION_DICT[0][serverNum]["channel"][serverChannel]["ip"]"};
System.IO.StreamWriter file = new System.IO.StreamWriter(path);
file.WriteLine(lines);
file.Close();
I almost forgot I want more lines, this program is trimmed
You can escape those characters with a slash:
string[] lines = {
" import serverInfo" ,
"serverNum=1" ,
"serverChannel=1" ,
"addr_new = serverInfo.REGION_DICT[0][serverNum][\"channel\"][serverChannel][\"ip\"] "};
or use a #-quoted string and use "" instead of " like so:
string[] lines = {
" import serverInfo" ,
"serverNum=1" ,
"serverChannel=1" ,
#"addr_new = serverInfo.REGION_DICT[0][serverNum][""channel""][serverChannel][""ip""] "};
You need to concatenate the strings:
"addr_new = serverInfo.REGION_DICT[0][serverNum][" + channel + "][serverChannel][" + ip + "]"};
Or if you wish for "channel" to be used as a string value, use single quotes:
"addr_new = serverInfo.REGION_DICT[0][serverNum]['channel'][serverChannel]['ip']"};
Escape the special characters
"addr_new = serverInfo.REGION_DICT[0][serverNum][\"channel\"][serverChannel][\"ip\"]"

Issue with forming a string with double quotes

I want to form a string as <repeat><daily dayFrequency="10" /></repeat>
Wherein the value in "" comes from a textboxe.g in above string 10. I formed the string in C# as
#"<repeat><daily dayFrequency=""+ txt_daily.Text + "" /></repeat>" but i get the output as
<repeat><daily dayFrequency="+ txt_daily.Text+ " /></repeat>. How to form a string which includes the input from a textbox and also double quotes to be included in that string.
To insert the value of one string inside another you could consider string.Format:
string.Format("foo {0} bar", txt_daily.Text)
This is more readable than string concatenation.
However I would strongly advise against building the XML string yourself. With your code if the user enters text containing a < symbol it will result in invalid XML.
Create the XML using an XML library.
Related
How can I build XML in C#?
Escape it with \ Back slash. putting # in front wont do it for you
string str = "<repeat><daily dayFrequency=\"\"+ txt_daily.Text + \"\" /></repeat>";
Console.Write(str);
Output would be:
<repeat><daily dayFrequency=""+ txt_daily.Text + "" /></repeat>
You could do it like this:
var str = String.Format(#"<repeat><daily dayFrequency="{0}" /></repeat>",
txt_daily.Text);
But it would be best to have an object that mapped to this format, and serialize it to xml
string test = #"<repeat><daily dayFrequency=" + "\"" + txt_daily.Text + "\"" + "/></repeat>";

Categories

Resources