文本文件中网站的内容

本文关键字:网站 文件 中网 文本 | 更新日期: 2023-09-27 18:33:46

我的目标是从网站(例如体育网站的排行榜)获取内容并将其放入.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文件,或者有没有办法修复提供的代码?

谢谢

文本文件中网站的内容

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

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

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

有没有更好的方法将内容从网站获取到.txt文件

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

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

另外,请确保释放 WebResponse,除了您的代码应该正常工作之外。