如何从互联网上读取文件?

32

简单问题: 我有一个在线文件(txt)。如何读取并检查它是否存在? (C#.net 2.0)

简化版翻译: 如何在C#.net 2.0中读取在线(txt)文件并判断其是否存在?

7个回答

86

1
你能填写这个的前提条件吗?我得到了“找不到类型或命名空间名称'WebClient'”的错误。 - jbyrd
WebClient可以在System.Net中找到 - 快速谷歌搜索“dotnet WebClient”通常会出现Microsoft参考页面,告诉您层次结构。 - Magnus Smith

22

来源于http://www.csharp-station.com/HowTo/HttpWebFetch.aspx

    HttpWebRequest  request  = (HttpWebRequest)
        WebRequest.Create("myurl");

        // 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?

    // print out page source
    Console.WriteLine(sb.ToString());

9
现在这个过程非常简单:只需要实例化一个 WebClient 然后调用它的 DownloadString 方法即可。 - Matt Tsōnto
1
变量sbbuf来自哪里?此外,该链接现在已失效。 - jbyrd
1
sb 是 StringBuilder,buf 是 Byte[]。 - Julius Prayogo

10
一个更简单的方法:
string fileContent = new WebClient().DownloadString("yourURL");

WebClient已经过时,请使用HttpClient代替。 - ADM-IT

8

首先,您可以下载二进制文件:

public byte[] GetFileViaHttp(string url)
{
    using (WebClient client = new WebClient())
    {
        return client.DownloadData(url);
    }
}

然后,您可以创建一个字符串数组来表示文本文件(假设为UTF-8编码和文本文件):

var result = GetFileViaHttp(@"http://example.com/index.html");
string str = Encoding.UTF8.GetString(result);
string[] strArr = str.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);

您将收到每个数组字段中的每个(非空)文本行。


1
这是针对Windows行尾编码的。如果您希望将行拆分为Linux,请使用“\n”。 - pbies
最好使用 new string[] { Environment.NewLine } 作为通用解决方案。 - Wajdy Essam

4

HttpWebRequest的替代方案是WebClient

    // create a new instance of WebClient
    WebClient client = new WebClient();

    // set the user agent to IE6
    client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705;)");
    try
    {
        // actually execute the GET request
        string ret = client.DownloadString("http://www.google.com/");

        // ret now contains the contents of the webpage
        Console.WriteLine("First 256 bytes of response: " + ret.Substring(0,265));
    }
    catch (WebException we)
    {
        // WebException.Status holds useful information
        Console.WriteLine(we.Message + "\n" + we.Status.ToString());
    }
    catch (NotSupportedException ne)
    {
        // other errors
        Console.WriteLine(ne.Message);
    }

来自http://www.daveamenta.com/2008-05/c-webclient-usage/的示例:


0

这太容易了:

using System.Net;
using System.IO;

...

    using (WebClient client = new WebClient()) {
        //... client.options
        Stream stream = client.OpenRead("http://.........");
        using (StreamReader reader = new StreamReader(stream)) {
            string content = reader.ReadToEnd();
        }
    }

"

“WebClient” 和 “StreamReader” 都是可处置的。文件内容将存储到 “content” 变量中。

客户端变量包含多个配置选项。

默认配置可以称为:

"
string content = new WebClient().DownloadString("http://.........");

-2
看看 System.Net.WebClient,文档甚至有一个检索文件的示例。
但是测试文件是否存在意味着请求该文件并捕获异常(如果不存在)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接