来自网站的文字内容

时间:2016-02-08 15:43:02

标签: c# file web

我的目标是从网站上获取内容(例如体育网站的联赛表)并将其放在.txt文件中,以便我可以使用本地文件进行编码。

我尝试了多行代码和其他示例,例如:

// prepare the web page we will be asking for
    HttpWebRequest request = (HttpWebRequest)
        WebRequest.Create("http://www.stackoverflow.com");
// prepare the web page we will be asking for
    HttpWebRequest request = (HttpWebRequest)
        WebRequest.Create("http://www.stackoverflow.com");

    // execute the request
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();

    // we will read data via the response stream
    Stream resStream = response.GetResponseStream();

    string tempString = null;
    int count = 0;
    do
    {
        // fill the buffer with data
        count = resStream.Read(buf, 0, buf.Length);

        // make sure we read some data
            if (count != 0)
        {
        // translate from bytes to ASCII text
        tempString = Encoding.ASCII.GetString(buf, 0, count);

        // continue building the string
        sb.Append(tempString);
        }
    while (count > 0); // any more data to read?
    }

我的问题是,在尝试此操作时,请求和响应是否在读取时加下划线并且所有令牌都无效。 有没有更好的方法将网站内容提供到.txt文件,还是有办法修复提供的代码?

由于

1 个答案:

答案 0 :(得分:0)

  

有没有办法修复提供的代码?

您提交的代码适合我,请确保您定义了正确的名称空间。 在这种情况下:using System.Net;

或者可能是变量请求的重复创建不是一个错字? 如果是,请删除其中一个请求变量。

  

是否有更好的方法可以将网站内容转换为.txt文件

由于您无论如何都要阅读网站上的所有内容,因此并不需要while循环。相反,您可以使用StreamReader提供的ReadToEnd方法。

string siteContent = "";    
using (StreamReader reader = new StreamReader(resStream)) {
   siteContent = reader.ReadToEnd();
}

另外请务必处理WebResponse,除此之外,您的代码应该可以正常工作。

相关问题