![](/img/trans.png)
[英]Getting streamreader to read specific line in text file, then write to console c#
[英]StreamReader C# - read only a specific line
我试图仅从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>”并且不打印任何其他内容(或该行之后的任何内容)。
我该怎么做呢?
谢谢
如果您需要读取特定的行而不是使用ReadToEnd
,那么您应该考虑使用ReadLine
,那么您应该能够计算读取的行数,以便知道何时到达所需的行。
您可以将所有行读入数组,以便通过索引引用特定行。
构建扩展方法:
public static IEnumerable<string> ReadLines(this StreamReader reader)
{
yield return reader.ReadLine();
}
然后你可以使用LINQ选择你想要的任何行,下面的例子是选择第三行:
var result = streamReader.ReadLines()
.ElementAtOrDefault(2);
您仍然可以通过这种方式利用延迟执行
正则表达式会做到这一点。 简单的例子:
string test = @"<html>\n<head>\n<title>Access is Granted.</title>\n<style>...";
string output = Regex.Match(test, "<title>.*</title>").Value;
如何使用XmlReader
从HTML文档中读取所需的确切值? 由于XmlReader
是流式传输,因此您不必像使用数组方法那样费心阅读整个文档,它会自动为您解析它。 这比依赖于某一行上的<title>
标记更安全。
using(var reader = XmlReader.Create(myHttpWebResponse.GetResponseStream()))
{
reader.ReadToDescendant("title");
var result = "<title>" + reader.ReadElementString() + "</title>";
Log("Access", Server.HtmlEncode(result), "Success");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.