32

simple question: I have an file online (txt). How to read it and check if its there? (C#.net 2.0)

7 Answers 7

86

I think the WebClient-class is appropriate for that:  

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

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

2
  • 1
    Could you fill in the prerequisites for this? I'm getting The type or namespace name 'WebClient' could not be found
    – jbyrd
    Commented Feb 27, 2018 at 19:33
  • WebClient can be found in System.Net - a quick Google for "dotnet WebClient" usually turns up the Microsoft reference page which tells you the hierarchy. Commented Mar 22, 2021 at 8:50
22

from 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());
3
  • 9
    Nowadays it's much simpler: just instantiate a WebClient and call DownloadString on it. Commented Mar 20, 2016 at 19:34
  • 1
    Where do the variables sb and buf come from? Also the link is dead now.
    – jbyrd
    Commented Feb 27, 2018 at 19:38
  • 1
    sb is StringBuilder and buf is Byte[] Commented Jul 26, 2018 at 9:41
11

A little bit easier way:

string fileContent = new WebClient().DownloadString("yourURL");
1
  • WebClient is obsolete. Use HttpCLient instead.
    – ADM-IT
    Commented May 14, 2022 at 10:17
8

First, you can download the binary file:

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

Then you can make array of strings for text file (assuming UTF-8 and that it is a text file):

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

You'll receive every (except empty) line of text in every array field.

2
  • 1
    This is for Windows line ending encoding. If you wish to split lines for Linux use "\n".
    – pbies
    Commented Jul 28, 2016 at 16:40
  • better to use new string[] { Environment.NewLine } for generic soltuion Commented Apr 17, 2022 at 22:43
4

an alternative to HttpWebRequest is 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);
    }

example from http://www.daveamenta.com/2008-05/c-webclient-usage/

0

This is too much easier:

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" and "StreamReader" are disposables. The content of file will be into "content" var.

The client var contains several configuration options.

The default configuration could be called as:

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

Look at System.Net.WebClient, the docs even have an example of retrieving the file.

But testing if the file exists implies asking for the file and catching the exception if it's not there.

Not the answer you're looking for? Browse other questions tagged or ask your own question.