简体   繁体   中英

StreamReader C# - read only a specific line

I am trying to log only 3rd line (or lines 1 to 3 if logging just one line is not possible) from a webResposne.

here is a snippet of the code that I am using for now.

StreamReader read = new StreamReader(myHttpWebResponse.GetResponseStream(), System.Text.Encoding.UTF8);
        String result = read.ReadToEnd();
        Log("Access", Server.HtmlEncode(result), "Success");

I am getting the following output

<html>
<head>
    <title>Access is Granted.</title>
    <style>
     body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} 
     p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
     b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
     H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
     H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
...

and so on.

I would just like to log "(title>Access is Granted.(/title>" and not print anything else (or anything after that line).

How would I go about doing that?

Thank you

如果您需要读取特定的行而不是使用ReadToEnd ,那么您应该考虑使用ReadLine ,那么您应该能够计算读取的行数,以便知道何时到达所需的行。

您可以将所有行读入数组,以便通过索引引用特定行。

Build extension method:

public static IEnumerable<string> ReadLines(this StreamReader reader)
{
     yield return reader.ReadLine();
}

Then you can use LINQ to select any line you want, example below is to select the third line:

 var result  = streamReader.ReadLines()
                           .ElementAtOrDefault(2);

You still take advantage of deferred execution on this way

Regex will do the trick. Simple example:

string test = @"<html>\n<head>\n<title>Access is Granted.</title>\n<style>...";
string output = Regex.Match(test, "<title>.*</title>").Value;

Use HtmlAgilityPack .

Run the response through it and extract the line(s) you need.

Plain and simple

How about using an XmlReader to read the exact value you want from the HTML document? Since XmlReader is streaming you won't have to bother reading the entire document as with the array method, and it will automatically parse it for you. This is safer than relying on the <title> tag being on a certain line.

using(var reader = XmlReader.Create(myHttpWebResponse.GetResponseStream()))
{
    reader.ReadToDescendant("title");
    var result = "<title>" + reader.ReadElementString() + "</title>";
    Log("Access", Server.HtmlEncode(result), "Success");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM