C# passing quotes in string - c#

I am trying to pass quotes in string. I am having a hard time formulating the code.
path = path.Insert(0, #"\\ffusvintranet02\picfiles\temp\");
string format = "Set-UserPhoto ";
format += "" + user + "";
format += " -PictureData ([System.IO.File]::ReadAllBytes(";
format += "" + path + #"";
format += ")";
The user and path are variables that needs to be inside single quotes for the AD Command. command. What I have isn't working.

User \" for " symbol or \' for '
format += "\"" + user + "\"";

First of all , use string.format for such tasks. Second you have to escape quotes ( but you dont need to escape single quotes).
Double quotes can be escaped by double quote or by backslash based on type of string literal you are using:
var s = #"something "" somethin else "; // double double quote here
var s2 = "something \" somethin else ";
Now, using string.format, your code will turn into:
path = path.Insert(0, #"\\ffusvintranet02\picfiles\temp\");
string format = string.format("Set-UserPhoto {0} -PictureData ([System.IO.File]::ReadAllBytes(\"{1}\")", user, path);
or
path = path.Insert(0, #"\\ffusvintranet02\picfiles\temp\");
string format = string.format(#"Set-UserPhoto {0} -PictureData ([System.IO.File]::ReadAllBytes(""{1}"")", user, path);

string format = "Set-UserPhoto "; format += "'" + user + "'"; format += " -PictureData ([System.IO.File]::ReadAllBytes("; format += "'" + path + #"'"; format += ")";

I would suggest using string interpolation within a here-string as follows, this will prevent you from having to use string concatenation and escaping.
$format = #"
Set-UserPhoto " + user + " -PictureData ([System.IO.File]::ReadAllBytes(" + path + ")"
"#

Related

Add double quotes to variable name for MS Deploy code in c#

Its a c# code written in a SSIS script task component.
PS_script + #"""$compname = " "\" + Row.computername"\" +
"$appname =" + Row.applicationname + " $appvalue = " + Row.appvalue +
"";
I am tying the MS deploy and setting params coming from table driven. The above statement throws error as I am not able to pass double quotes in computername param.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/verbatim
In C#, a literal string with the prefix #, "" will be replaced by ".
Example :
var str = #"$compname = """ + Row.computername + #"""";
If the variable Row.computername has the value SERV01, then the result will be :
$compname = "SERV01"
You can also escape a character with \. Then \" will be replaced by ".
Example :
var str = "$compname = \"" + Row.computername + "\"";
If the variable Row.computername has the value SERV01, then the result will be :
$compname = "SERV01"
In you case, you can also use string.Format to more lisibility :
string.Format(
#" $compname = ""{0}"" $appname = ""{1}"" $appvalue = ""{2}""",
Row.computername, Row.applicationname, Row.appvalue
);
Warning, with SSIS script task, you can't use string interpolation (the literal string prefix $).

C# Creating white space lines between assembled .text

private void btnAssemble_Click(object sender, EventArgs e)
{
txtAssembled.Text = (cboTitle.Text + txtFirstName.Text[0] + txtMiddle.Text + txtLastName.Text + "\r\n" +txtStreet.Text + "\r\n"+ cboCity.Text);
}
I'm trying to get 1 character white space inbetween cboTitle.Text, txtFirname.Text, txtMiddle.Text, and txtLastName, but they all output the information together, but I want them spaced evenly. what do I need to do? thanks in advance.
I'm going to post some other code thats below the one above in my project, just in case it might be relevant.
string AssembleText(string Title, string FirstName, string MiddleInitial, string LastName, string AddressLines, string City )
{
string Result = "";
Result += Title + " ";
Result += FirstName.Substring(0, 2) + " ";
// Only append middle initial if it is entered
if (MiddleInitial != "")
{
Result += MiddleInitial + " ";
}
Result += LastName + "\r\n";
// Only append items from the multiline address box
// if they are entered
if ( AddressLines != "")
{
Result += AddressLines + "\r\n";
}
//if (AddressLines.Length > 0 && AddressLines.ToString() != "")
//{
// Result += AddressLines + "\r\n";
//}
Result += City;
return Result;
}
}
}
If you just want a space between those specific fields in btnAssemble_Click, you can just insert them like this:
string myStr = foo + " " + bar + " " + baz;
So your first function would be modified to read:
private void btnAssemble_Click(object sender, EventArgs e)
{
txtAssembled.Text = (cboTitle.Text + " " + txtFirstName.Text[0] + " " + txtMiddle.Text + " " + txtLastName.Text + "\r\n" + txtStreet.Text + "\r\n" + cboCity.Text);
}
A few other comments:
It's not clear to me what the AssembleText() function you posted has to do with this. I am confused though, as I see a few lines appending spaces at the end just like I mentioned above.
Using the String.Format() function may make this code easier to read and maintain.
Using Environment.NewLine instead of "\r\n" will make the string contain the newline character defined for that specific environment.
Using a StringBuilder object may be faster over concatenation when building strings inside of a loop (which may not apply here).
Using String.format() should feet the bill. It also make your code easy to read.
txt.assembled.text = String.Format("{0} {1} {2} {3}",
cboTitle.Text,
txtFirstName.Text[0],
txtMiddle.Text,
txtLastName.Text
);
It would be like this
private void btnAssemble_Click(object sender, EventArgs e)
{
txtAssembled.Text = (cboTitle.Text + " " + txtFirstName.Text[0] + " " +txtMiddle.Text + " " + txtLastName.Text + "\r\n" +txtStreet.Text + "\r\n"+ cboCity.Text);
}
It seems that you want String.Join; whenever you want to combine strings with a delimiter, say, " " (space) all you need is to put
String combined = String.Join(" ",
cboTitle.Text,
txtFirstName.Text[0],
txtMiddle.Text,
txtLastName.Text);
Complete implementation (joining by space and new line) could be
txtAssembled.Text = String.Join(Environment.NewLine,
String.Join(" ",
cboTitle.Text,
txtFirstName.Text[0],
txtMiddle.Text,
txtLastName.Text),
txtStreet.Text,
cboCity.Text);

New line in textbox

I have a textbox1 that lets the user input a text, a button that adds the text to textbox2.
this is my code but it doesnt create a new line when I add another text.
string date = DateTime.Now.ToString();
txt_details.Text = date + " " + txt_summary.Text.ToString() + Environment.NewLine + Environment.NewLine ;
Notice the += operator.
txt_details.Text += "\n" + date + " " + txt_summary.Text.ToString();
Looks like you should be appending (use +=); instead you are overwriting.
string date = DateTime.Now.ToString();
txt_details.Text += date + " " + txt_summary.Text.ToString() + Environment.NewLine + Environment.NewLine
Make sure Multiline is enabled.
Ensure that TextBox.Multiline property is set to true
txt_details.Multiline = true;

replace characters in result

I need to replace the characters ; and linebreak to the field p.notas. I tried this but it doesn't replace the linebreaks.
var res = from p in miDataContext.clientes
orderby p.nombreCom
select
(p.nombreCom ?? "") + ";" +
(p.razon ?? "") + ";" +
(p.nif ?? "") + ";" +
((p.notas ?? "").Replace (";" ,"."))
.Replace(Environment.NewLine , ". ");
The problem with using Environment.NewLine in your Replace() call is that the newline character(s) in your environment my not necessarily match what is actually used in the string. Yours probably has \r\n (windows) but what is actually stored is just \n. That pattern is definitely not in the string in that case. You'll have to check for all newline variants.
Assuming this is all fine in LINQ to SQL, just add more replace calls for each of the newline types.
var res = from p in miDataContext.clientes
orderby p.nombreCom
select
(p.nombreCom ?? "") + ";" +
(p.razon ?? "") + ";" +
(p.nif ?? "") + ";" +
((p.notas ?? "").Replace(";", "."))
.Replace("\r\n", ". ")
.Replace("\n", ". ")
.Replace("\r", ". ");

Help with simplifying a couple of regex's

Below I have two regex's that operate on some text:
assume key = "old" and value = "new"
text = Regex.Replace(text,
"\\." + change.Key + ",",
"." + change.Value + ","
);
text = Regex.Replace(text,
"\\." + change.Key + ";",
"." + change.Value + ";"
);
So, ".old," and ".old;" would change to ".new," and ".new;", respectively.
I'm sure this could be shortened to one regex. How can I do this so that the string only changes when the comma and semicolon are at the end of the variable? For example, I don't want ".oldQ" to change to ".newQ". Thanks!
.NET uses $ for backreferences:
text = Regex.Replace(text,
#"\." + change.Key + "([,;])",
"." + change.Value + "$1");
Out of my head:
text = Regex.Replace(text, #"\.(old|new),",#"\.\1;");
You want to just change the middle part, so:
text = Regex.Replace(text,
"\\." + change.Key + "(,|;)^", // mark a group using "()" for substitution...
"." + change.Value + "\1" // use the group ("\1")
);
I like using \b, like this:
text = Regex.Replace(text, #"\." + change.Key + #"\b", "." + change.Value);
It would match on keywords followed by other delimiters, not just "," and ";", but it may still work in your case.

Categories