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

Kov*_*ovu 25 c# file

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

Pbi*_*off 73

我认为WebClient类适合于此:  

WebClient client = new WebClient();
Stream stream = client.OpenRead("http://yoururl/test.txt");
StreamReader reader = new StreamReader(stream);
String content = reader.ReadToEnd();
Run Code Online (Sandbox Code Playgroud)

http://msdn.microsoft.com/en-us/library/system.net.webclient.openread.aspx


Rus*_*een 21

来自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());
Run Code Online (Sandbox Code Playgroud)

  • 现在它更简单:只需实例化一个`WebClient`并在其上调用`DownloadString`. (8认同)

pbi*_*ies 7

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

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

然后你可以为文本文件创建字符串数组(假设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);
Run Code Online (Sandbox Code Playgroud)

您将在每个数组字段中收到每个(除空)文本行.


dan*_*l89 5

更简单的方法:

string fileContent = new WebClient().DownloadString("yourURL");
Run Code Online (Sandbox Code Playgroud)