Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

efficient way to find string with streamreader

Tags:

c#

I get web response and use streamreader to obtain the response as a string

my code is

HttpWebResponse response = (HttpWebResponse) request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string strResponse = reader.ReadToEnd();

sample of string is

<div class="box-round">
<ol  style="list-style-type: decimal;list-style-position:outside;margin-left:42px;">
<li>Order ID #A123456 already exists: Update performed
</ol>
</div>

or

<div class="box-round">
    <ol  style="list-style-type: decimal;list-style-position:outside;margin-left:42px;">
    <li>New order created
    </ol>
</div>

I want to locate the following line within the string

Order ID #A123456 already exists: Update performed

or

New order created

Is this the best way to search for the line(s)

  while (!reader.EndOfStream)
    {
        line = reader.ReadLine();
        if (!string.IsNullOrEmpty(line))
        {

        }
    }
like image 459
CapsLock Avatar asked Aug 04 '11 23:08

CapsLock


People also ask

How do I use StreamReader?

Read); //Create an object of StreamReader by passing FileStream object on which it needs to operates on StreamReader sr = new StreamReader(fs); //Use the ReadToEnd method to read all the content from file string fileContent = sr. ReadToEnd(); //Close the StreamReader object after operation sr. Close(); fs. Close();

What is the difference between a StreamReader and file ReadAllLines?

The StreamReader read the file line by line, it will consume less memory. Whereas, File. ReadAllLines read all lines at once and store it into string[] , it will consume more memory.

How does a StreamReader differ from a StreamWriter?

A StreamReader is used whenever data is required to be read from a file. A Streamwriter is used whenever data needs to be written to a file.


2 Answers

Well, personally I would use:

string line;

while ((line = reader.ReadLine()) != null)
{
    if (line.Contains(...))
    {
    }
}

Reading the line gives you the data and tells you whether you've reached the end of the stream. I agree with Jeff though - "parsing" HTML by reading it line by line is generally a bad idea. It may be good enough in your specific situation, of course.

like image 196
Jon Skeet Avatar answered Oct 09 '22 00:10

Jon Skeet


Here's how to do it with regex, sure regex isn't the best method, but if this is a one time thing working with an html parser is probably more than you are bargaining for

Match myMatch = Regex.Match(input, 
       @"<div class=""box-round"">.*?<li>(.*?)</ol>", Regex.Singleline);

if (myMatch.Success)
{

}
like image 39
BenH Avatar answered Oct 09 '22 01:10

BenH