Issue with forming a string with double quotes - c#

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>";

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");

C# split received string based on a separator and save into multiple variables

I have a simple socket server which is receiving a string from client, now i am trying to split the received string and save it into multiple variables.
this is an example string (will be different depending of different clients):
Value0_Value1_Value2_Value3_Value4_END5
this is the section of the code for splitting the string :
if (content.IndexOf("END5") > -1)
{
// All the data has been read from the
// client. Display it on the console.
Console.WriteLine(content);
//split the received string and save into Splitdata1 Arr[]
string[] Splitdata1 = content.Split('_');
//Save each split value into a separate variable
string proce0 = Splitdata1[0];
string proce1 = Splitdata1[1];
string proce2 = Splitdata1[2];
string proce3 = Splitdata1[3];
string proce4 = Splitdata1[4];
string proce5 = Splitdata1[5];
//Print each value individually
Console.WriteLine("individual strings: \n", "proce0", proce0,
"\n", "proce1", proce1,
"\n", "proce2", proce2,
"\n", "proce3", proce3,
"proce4", proce4, "\n",
"proce5", proce5 );
// Echo the data back to the client.
Send(handler, content);
}
and this is the console output that i am getting when i send the string from client:
Waiting for a connection...
Value0_Value1_Value2_Value3_Value4_END5
individual strings:
Sent 40 bytes to client.
I am not sure if its not splitting the string at all , or its just not printing the 6 string variables.
What am i doing wrong ?
Console.Writeline(String, Object[]) expects you to provide a composite format string as your first argument, followed by the objects to write using that format string. In your case, you do not have any indexed placeholders in your first argument, so the subsequent arguments are ignored.
You can fix this by replacing your Console.WriteLine call with the below:
Console.WriteLine("individual strings:\n" +
$"proce0: {proce0}\n" +
$"proce1: {proce1}\n" +
$"proce2: {proce2}\n" +
$"proce3: {proce3}\n" +
$"proce4: {proce4}");
Console.WriteLine(string format, params object?[]? arg) does doesn't accept arguments in that manner.
What you are doing is trying to insert the objects into a formattable string, the equivalent is using string.Format. Which will not work properly because you do not specify the index inside the string. It should look like -
// string.Format equivalent
Console.WriteLine("individual strings:\n" +
"proce0: {0}\n" +
"proce1: {1}\n" +
"proce2: {2}", proce0, proce1, proce2);
// string interpolation
Console.WriteLine("individual strings:\n" +
$"proce0: {proce0}\n" +
$"proce1: {proce1}\n" +
$"proce2: {proce2}");
There is also a way to do it without specifying each variable. So even if you send more data then expected it will display all data split on the '_' char regardless.
Console.WriteLine("individual strings:")
foreach(var data in Splitdata1)
{
Console.WriteLine(data);
}
Console.WriteLine("individual strings: \n", "proce0", proce0,"\n", "proce1", proce1,"\n", "proce2", proce2, "\n", "proce3", proce3,"proce4", proce4, "\n","proce5", proce5 );
This line doesn't concatenate the string together.
The first string need to contain where you want your other objects to be concatenate.
Like that:
Console.WriteLine($"individual strings: \n proce0: {proce0} \n proce1: {proce1} \n proce2: {proce2} \n proce3: {proce3} \n proce4: {proce4} \n proce5: {proce5}");

StreamReader from .csv - "foreign" chars and blank values showing up as '?'

I'm having two problems with reading my .csv file with streamreader. What I'm trying to do is get the values, put them into variables which I'll be using later on, inputting the values into a browser via Selenium.
Here's my code (the Console.Writeline at the end is just for debugging):
string[] read;
char[] seperators = { ';' };
StreamReader sr = new StreamReader(#"C:\filename.csv", Encoding.Default, true);
string data = sr.ReadLine();
while((data = sr.ReadLine()) != null)
{
read = data.Split(seperators);
string cpr = read[0];
string ydelsesKode = read[1];
string startDato = read[3];
string stopDato = read[4];
string leverandoer = read[5];
string leverandoerAdd = read[6];
Console.WriteLine(cpr + " " + ydelsesKode + " " + startDato + " " + stopDato + " " + leverandoer + " " + leverandoerAdd);
}
The code in and of itself works just fine - but I have two problems:
The file has values in Danish, which means I get åøæ, but they're showing up as '?' in console. In notepad those characters look fine.
Blank values also show up as '?'. Is there any way I can turn them into a blank space so Selenium won't get "confused"?
Sample output:
1372 1.1 01-10-2013 01-10-2013 Bakkev?nget - dagcenter ?
Bakkev?nget should be Bakkevænget and the final '?' should be blank (or rather, a bank space).
"Fixed" it by going with tab delimited unicode .txt file instead of .csv. For some reason my version of excel doesn't have the option to save in unicode .csv...
Don't quite understand the problem of "rolling my own" parser, but maybe someday someone will take the time to explain it to me better. Still new-ish at this c# stuff...

String.Replace Not modifying my String

I am trying to save a number of images and I'd like to use the DateTime to have distinct and identifiable Filenames.
So I create a String with the correct Path, add the datetime to it and remove the spaces, dots and colons.
String imagePath = "D:\\Patienten\\" + username;
imagePath += "\\"+DateTime.Now.ToString();
Console.WriteLine("WithFilename: " + imagePath);
imagePath.Replace(" ", "");
Console.WriteLine("Without \" \" : " + imagePath);
imagePath.Replace(".", "");
Console.WriteLine("Without \".\": " + imagePath);
imagePath.Replace(":", "");
Console.WriteLine("Output format: " + imagePath);
imagePath += ".png";
image.Save(imagePath);
According to the console output the String doesnt change at all.
Meaning all the Output Strings from Console.Writeline are identical.
I am using c# in visual Studio Express 2010 in case that makes a difference.
Can anyone find an Error here?
Thanks in advance!
Strings are immutable, the modified string will be a new string that is returned from the function
e.g.
imagePath = imagePath.Replace(" ", "");
Why strings are immutable
Why not just use DateTime.ToString() with a format and drop the dividers using that? Would be more efficient than performing several String.Replace() yourself:
string imagePath = "D:\\Patienten\\" + username + "\\" + DateTime.Now.ToString("yyyyMMdd hhmmssfff") + ".png";
You should use:
imagePath = imagePath.Replace(" ", ""); You should assign returned value
From the documentation (emphasis mine):
Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.
It is supposed to work like that. Use
imagePath = imagePath.Replace(" ", "");
instead.

string.replace() not working with xml string

I have read all similar questions and acted accordingly. But still can't figure out what's wrong with my code.
This is my code, super simple. (I know this isn't valid XML. It's just for the example).
string replacement = "TimeSheetsReplaced";
string word = "TimeSheets";
string result = "<?xml version=\"1.0\" encoding=\"utf-16\"?><DisplayName>Timesheets</DisplayName>";
result = result.Replace("<DisplayName>" + word + "</DisplayName>", "<DisplayName>" + replacement + "</DisplayName>");
The result string remains unplaced. What am I doing wrong??
TimeSheets != Timesheets
Casing does not match
It's because your string contains Timesheets, but you're lokoing for TimeSheets (with a capital S).
In your word TimeSheets has big S, in string small s

Categories

Resources