4

使用应用程序来解析 robots.txt。我给自己写了一个从网络服务器中提取文件的方法,然后把输出扔到一个文本框中。我希望输出为文件中的每一行显示一行文本,就像您正常查看 robots.txt 时会出现的那样,但是我的文本框中的输出是所有没有的文本行回车或换行。所以我想我会很狡猾,为所有行制作一个 string[],制作一个 foreach 循环,一切都会好起来的。唉,那不起作用,所以我想我会尝试 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);
    }
}
4

4 回答 4

7

您正在将整个文件读入lines数组的第一个元素:

string[] lines = new string[] {read.ReadToEnd()};

因此,您的所有循环所做的就是将文件的全部内容添加到 TextBox 中,然后是换行符。用这些替换该行:

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);
}
于 2010-08-06T09:03:36.643 回答
2

您需要使 textBox1 多行。然后我想你可以简单地去

textBox1.Lines = lines;

但让我检查一下

于 2010-08-06T08:57:18.577 回答
1

尝试在 while 循环中使用 .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();
于 2010-08-06T09:04:19.777 回答
1

尝试

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();
}
于 2010-08-06T09:06:53.297 回答