StreamReader C# - 只读特定行

本文关键字:只读 StreamReader | 更新日期: 2023-09-27 17:56:16

我试图从webResposne只记录第3行(如果只记录一行,则记录第1到3行)。

这是我现在使用的代码片段。

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

我得到以下输出

<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 }
...

等等。

我只想记录"(标题>访问权限已授予。/title>",并且不打印任何其他内容(或该行之后的任何内容)。

我该怎么做呢?

谢谢

StreamReader C# - 只读特定行

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

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

正则表达式可以做到这一点。简单的例子:

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

构建扩展方法:

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

然后,您可以使用 LINQ 选择所需的任何行,下面的示例是选择第三行:

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

您仍然以这种方式利用延迟执行

使用HtmlAgilityPack。

通过它运行响应并提取所需的行。

简单明了

使用XmlReader从HTML文档中读取您想要的确切值怎么样?由于XmlReader是流式传输,因此您不必像使用 array 方法那样费心阅读整个文档,它会自动为您解析它。这比依赖<title>标签在某一行上更安全。

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