Click here to Skip to main content
15,888,454 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So I have some code that gets the HTML from a website and I am going to do stuff with thy HTML , but I do not want to repeatedly request the HTML code each time i need to extract data from it in different subroutines so was wondering if there was a way to use the ImpureText string in another Subroutine.



````` public static string ExtractingHTML(string urlAddress)
{

// string urlAddress = "https://www.bbc.co.uk/news/uk-politics-50305284";

string ImpureText = string.Empty;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

if (response.StatusCode == HttpStatusCode.OK)
{
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = null;

if (response.CharacterSet == null)
{
readStream = new StreamReader(receiveStream);

}
else
{
readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
readStream.ToString();
//Console.WriteLine(readStream);
}

string data = readStream.ReadToEnd();

ImpureText = data.ToString();

Console.WriteLine(ImpureText); //


}
return ImpureText;


}

public static void TitleExtraction()
{
string Titlestart = $"<title>";
string Titleend = $"";

int titlestart = ImpureText.IndexOf(Titlestart) + Titlestart.Length; //From here to //this regex breaks it
int titleend = ImpureText.IndexOf(Titleend);
string PureTexttitle = ImpureText.Substring(titlestart, titleend - titlestart);
Console.WriteLine("Title-" + PureTexttitle);



} ````

What I have tried:

I thought of adding the ImpureText to a file but its rather inefficient
i also turned the subroutine into a function instead of a method but i probably did it wrong.


Thankyou
Posted
Updated 23-Nov-19 4:23am
Comments
Richard MacCutchan 23-Nov-19 9:29am    
Don't use a local variable in the method that captures the text (as you have done here). Declare the variable at class level so it is accessible from all methods of the class.

1 solution

Since it's a static method, you have two choices:
1) Can be complicated: modify all methods that need to access it to accept it as a parameter, and pass it round the system. This is good if you expect multiple instances of your class
2) Simple: move the definition outside the method. Declare it outside the method as
C#
private static string impureText = "";
And remove the definition inside your method. Any member of the class can now access it.
This is bad if more than one instance needs to access it, as there will only be one impureText variable for your whole class.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900