用C#在机器人中解析单个行。TXT文件
-
26-09-2019 - |
题
在解析robots.txt的应用程序上工作。我写了一种方法,将文件从Web服务器中提取,然后将OUPUT扔进文本框中。我希望输出能为文件中的每一行显示一行文本行,就像您正在查看robots.txt的情况一样,但是我的文本框中的ouput是所有文本行,没有任何文本行马车返回或线路断路。因此,我以为我会很狡猾,为所有行制作一个弦[],做一个foreach循环,一切都会好起来的。 las不起作用,所以我以为我会尝试system.enviornment.newline,仍然不起作用。这是现在听起来的代码。...我该如何更改它,以便我获得所有单独的robots.txt行,而不是拼凑在一起的一堆文本?
public void getRobots()
{
WebClient wClient = new WebClient();
string url = String.Format("http://{0}/robots.txt", urlBox.Text);
try
{
Stream data = wClient.OpenRead(url);
StreamReader read = new StreamReader(data);
string[] lines = new string[] { read.ReadToEnd() };
foreach (string line in lines)
{
textBox1.AppendText(line + System.Environment.NewLine);
}
}
catch (WebException ex)
{
MessageBox.Show(ex.Message, null, MessageBoxButtons.OK);
}
}
解决方案
您正在将整个文件读为 lines
大批:
string[] lines = new string[] {read.ReadToEnd()};
因此,您所做的所有循环都是将文件的整体内容添加到文本框中,然后是newline字符。用这些替换该行:
string content = read.ReadToEnd();
string[] lines = content.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
看看是否有效。
编辑: :根据Fish在下面关于逐行阅读的评论,一种替代方案,也许是更有效的方法 - 将代码置于 try
有这样的障碍:
Stream data = wClient.OpenRead(url);
StreamReader read = new StreamReader(data);
while (read.Peek() >= 0)
{
textBox1.AppendText(read.ReadLine() + System.Environment.NewLine);
}
其他提示
您需要制作TextBox1 Multiline。那我想你可以走
textBox1.Lines = lines;
但是让我检查一下
尝试
public void getRobots()
{
WebClient wClient = new WebClient();
string robotText;
string[] robotLines;
System.Text.StringBuilder robotStringBuilder;
robotText = wClient.DownloadString(String.Format("http://{0}/robots.txt", urlBox.Text));
robotLines = robotText.Split(Environment.NewLine);
robotStringBuilder = New StringBuilder();
foreach (string line in robotLines)
{
robotStringBuilder.Append(line);
robotStringBuilder.Append(Environment.NewLine);
}
textbox1.Text = robotStringBuilder.ToString();
}
尝试在一段时间内使用.read()而不是.readToend() - 我认为您只是将整个文件作为行数组中的一行。调试并检查行计数[]以验证这一点。
编辑:这是一些示例代码。尚未测试,但我认为它应该可以正常工作;
Stream data = wClient.OpenRead(url);
StreamReader read = new StreamReader(data);
List<string> lines = new List<string>();
string nextLine = read.ReadLine();
while (nextLine != null)
{
lines.Add(nextLine);
nextLine = read.ReadLine();
}
textBox1.Lines = lines.ToArray();
不隶属于 StackOverflow