Trying to use a .replace function to take out the breaks (<br> and </br>) though having trouble with the code I have been given.
Here is what I am working with.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
var rawStream = sr.ReadToEnd();
sr.Close();
var myBuilder = new StringBuilder();
myBuilder.AppendLine("Employee Name : " + rawStream.Between("<span id=\"Label_DisplayFullName\">", "</span>"));
myBuilder.AppendLine("Title: " + rawStream.Between("<span id=\"Label_Title\">", "</span>"));
myBuilder.AppendLine("Location : " + rawStream.Between("<span id=\"Label_Location\">", "</span>"));
myBuilder.AppendLine("Department : " + rawStream.Between("<span id=\"Label_Department\">", "</span>"));
myBuilder.AppendLine("Group: " + rawStream.Between("<span id=\"Label_Group\">", "</span>"));
myBuilder.AppendLine("Office Phone : " + rawStream.Between("<span id=\"Label_IntPhoneNumber\">", "</span>"));
myBuilder.AppendLine("Mobile Phone : " + rawStream.Between("<span id=\"Label_BusMobile\">", "</span>"));
richTextBox1.Text = myBuilder.ToString();
Though I understand the function should be like so:
public string Replace( string oldValue, string newValue )
I just dont understand how this works in my code as I dont really have a "string" but I have a string builder.
Any assistance would be huge.
What does all your StringBuilder stuff have to do with removing the breaks? Your string is in the rawStream variable (quite badly named) (that's what ReadToEnd() gives you), so you'd just:
rawStream = rawStream.Replace("<br>", "");
rawStream = rawStream.Replace("<br />");
There are two things you could do:
On the one hand, you do assemble your string with a StringBuilder, however, you eventually convert the contents of that string builder into a string when you call myBuilder.ToString(). That is where you could invoke Replace:
richTextBox1.Text = myBuilder.ToString().Replace("<br>", "").Replace("</br>", "");
Alternatively, StringBuilder has a Replace method of its own, so you could invoke that before transforming the string builder contents into a string:
myBuilder.Replace("<br>", "");
myBuilder.Replace("</br>", "");
Note that the latter can alternatively be invoked in a chained fashion, as well, though that is arguably less readable:
richTextBox1.Text = myBuilder.Replace("<br>", "").Replace("</br>", "").ToString();
Since replace returns string you can chain them
rawStream = rawStream.Replace("<br>","").Replace("<br/>","").Replace("<br />","");
Can't you just put it after the ToString() call?
richTextBox1.Text = myBuilder.ToString().Replace("string1", "string2");
As mentioned in the comments you can also call it on the stringbuilder object itself.
richTextBox1.Text = myBuilder.Replace("string1", "string2").ToString();
Try this.
richTextBox1.Text = myBuilder.Replace("<br>", String.Empty).Replace("</br>", String.Empty).ToString();
Or
var rawStream = sr.ReadToEnd().Replace("<br>", String.Empty).Replace("</br>", String.Empty);
Related
I'm creating a loop in which each line is a pretty long HTML line on the page. I've tried various combinations of # and """ but I just can't seem to get the hang of it
This is what I've got now, but the single quotes are giving me problems on the page, so I want to change all the single quotes to double quotes, just like a normal HTML line would use them for properties in the elements:
sOutput += "<div class='item link-item " + starOrBullet + "'><a href='" + appSet + linkID + "&TabID=" + tabID + "' target=’_blank’>" + linkText + "</a></div>";
variables are:
starOrBullet
appSet
LinkID
tabID (NOT $TabID=)
linkText
BTW, appSet="http://linktracker.swmed.org:8020/LinkTracker/Default.aspx?LinkID="
Can someone help me here?
You have to escape the double quotes (") with \"
For your case:
sOutput += "<div class=\"item link-item " + starOrBullet + "\"><a href=\"" + appSet + linkID + "&TabID=" + tabID + "\" target=’_blank’>" + linkText + "</a></div>";
If you concat many strings, you should use StringBuilder for performance reasons.
You can use a verbatim string and escape a double quote with a double quote. So it will be a double double quote.
tring mystring = #"This is \t a ""verbatim"" string";
You can also make your string shorter by doing the following:
Method 1
string mystring = #"First Line
Second Line
Third Line";
Method 2
string mystring = "First Line \n" +
"Second Line \n" +
"Third Line \n";
Method 3
var mystring = String.Join(
Environment.NewLine,
"First Line",
"Second Line",
"Third Line");
You must make habit to use C# class to generate Html instead concatenation. Please find below code to generate Html using C#.
Check this link for more information
https://dejanstojanovic.net/aspnet/2014/june/generating-html-string-in-c/
https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.htmltextwriter
Find below code for your question
protected void Page_Load(object sender, EventArgs e)
{
string starOrBullet = "star-link";
string appSet = "http://linktracker.swmed.org:8020/LinkTracker/Default.aspx?LinkID=";
string LinkID = "2";
string tabID = "1";
string linkText = "linkText_Here";
string sOutput = string.Empty;
StringBuilder sbControlHtml = new StringBuilder();
using (StringWriter stringWriter = new StringWriter())
{
using (HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter))
{
//Generate container div control
HtmlGenericControl divControl = new HtmlGenericControl("div");
divControl.Attributes.Add("class", string.Format("item link-item {0}",starOrBullet));
//Generate link control
HtmlGenericControl linkControl = new HtmlGenericControl("a");
linkControl.Attributes.Add("href", string.Format("{0}{1}&TabID={2}",appSet,LinkID,tabID));
linkControl.Attributes.Add("target", "_blank");
linkControl.InnerText = linkText;
//Add linkControl to container div
divControl.Controls.Add(linkControl);
//Generate HTML string and dispose object
divControl.RenderControl(htmlWriter);
sbControlHtml.Append(stringWriter.ToString());
divControl.Dispose();
}
}
sOutput = sbControlHtml.ToString();
}
So i have this piece of code:
MessageBox.Show("Welcome," + name.Substring(0, nome.IndexOf(" ")) + "!");
lets suppose the name is "Phiter Fernandes", ok it will say:
Welcome, Phiter!
But if the name is just "Phiter" it will stop and not run the rest of the code.
Obviously is because there are no spaces for the substring method to retrieve the first name.
But i don't want it to skip the rest of the code, i want it to work even if there is no space.
I tried using the try catch, just like this:
try
{
MessageBox.Show("Welcome," + name.Substring(0, nome.IndexOf(" ")) + "!");
}
catch
{
MessageBox.Show("Welcome," + name + "!");
}
It works, but there is an annoying sound when the code runs the catch.
Is there any other way around this? A different way of getting the first name, perhaps?
Try splitting the string wherever there is a space, and selecting the first element, which will always be the first name.
MessageBox.Show("Welcome," + name.Split(' ')[0] + "!");
You can try more than one options.
Replace usign Regex.
string input = "Your string " + "whitespace.";
string pattern = "\\s+";
string replacement = " ";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
check if space exists.
if(name.Contains(" "))
MessageBox.Show("Welcome," + name.Substring(0, nome.IndexOf(" ")) + "!");
trim spaces
string fullName = name;
var names = fullName.Split(' ');
string firstName = names[0];
MessageBox.Show("Welcome," + firstName + "!");
Let me know which one did you use!
I am getting a Formatexception from the below code. I can't seem to fix it. What is wrong? Thanks
var res = dropDown.SelectedValue;
var zip = String.Format("{0}/FileBrowser/FOLDERNAME/filer/" + temp + ", projectPath");
Due to {0} in the format string
"{0}/FileBrowser/FOLDERNAME/filer/" + temp + ", projectPath"
String.Format expects an argument after it.
Did you mean something like
var zip = String.Format("{0}/FileBrowser/FOLDERNAME/filer/{1}", projectPath, temp);
i have a string with an html code. i want to remove all html tags. so all characters between < and >.
This is my code snipped:
WebClient wClient = new WebClient();
SourceCode = wClient.DownloadString( txtSourceURL.Text );
txtSourceCode.Text = SourceCode;
//remove here all between "<" and ">"
txtSourceCodeFormatted.Text = SourceCode;
hope somebody can help me
Try this:
txtSourceCodeFormatted.Text = Regex.Replace(SourceCode, "<.*?>", string.Empty);
But, as others have mentioned, handle with care.
According to Ravi's answer, you can use
string noHTML = Regex.Replace(inputHTML, #"<[^>]+>| ", "").Trim();
or
string noHTMLNormalised = Regex.Replace(noHTML, #"\s{2,}", " ");
I am trying to download images. Their link may be image.png or http://www.example.com/image.png.
I made the image.png be added to the host and passed it to a list. So image.png is now http://www.example.com/image.png
But if the other type is used what I get is http://www.example.com//http://www.example.com/image.png
All I need is to get the string after the third slash. Here is some code I am tried to use:
try
{
path = this.txtOutput.Text + #"\" + str4 + etc;
client.DownloadFile(str, path);
}
catch(Exception e)
{
var uri = new Uri(str);
String host = (String) uri.Host;
String pathToFile = "http://" + host + "/";
int len = pathToFile.Length;
String fin = str.Substring(len, str.Length - len);
path = this.txtOutput.Text + #"\" + str4 + etc;
client.DownloadFile(fin, path);
}
What are these variables all about, like str4, etc and so on? Instead of the try catch you could check wheter the string is a valid uri. Give a look here. Try to debug you code line on line and check every single variable, then you will see which line makes the mistake.
EDIT
If I understodd you right, then this would be your solution:
string wrongResult = "example.com//http://www.example.com/image.png";
string shouldResult = "example.com/image.png";
int listIndexOfHttp = wrongResult.LastIndexOf("http:");
string correctResult = wrongResult.Substring(listIndexOfHttp);
When not please describe more specific from where you get this and it is always the same structure? or alaways different?