C# download file from the web

4.2k Views Asked by At

Is there a way to make the following function work via proxy?

public T[] ReadStream(System.IO.TextReader reader);

I want to be able to proxify the reader instance, so that it could download a file from the web on reading attempts and cache it somewhere.

Or maybe there is something default for this purpose?

3

There are 3 best solutions below

5
On BEST ANSWER

Use WebClient.DownloadFile. If you need a proxy, you can set the Proxy property of your WebClient object.

Here's an example:

using (var client = new WebClient())
{
    client.Proxy = new WebProxy("some.proxy.com", 8000);
    client.DownloadFile("example.com/file.jpg", "file.jpg");
}

You can also download the file by parts with a BinaryReader:

using (var client = new WebClient())
{
    client.Proxy = new WebProxy("some.proxy.com", 8000);

    using (var reader = new BinaryReader(client.OpenRead("example.com/file.jpg")))
    {
        reader.ReadByte();
        reader.ReadInt32();
        reader.ReadBoolean();

        // etc.
    }
}
0
On
var webRequestObject = (HttpWebRequest) WebRequest.Create("http://whatever");
var response = webRequestObject.GetResponse();
var webStream = response.GetResponseStream();
// Ta-da.
var reader = new StreamReader(webStream);
1
On

Perhaps this is what you want? I am also slightly confused by the wording of the question, given your comments to the previous answer.

public StreamReader GetWebReader(string uri)
{
    var webRequest = WebRequest.Create(uri);
    var webResponse = webRequest.GetResponse();
    var responseStream = webResponse.GetResponseStream();
    return new StreamReader(responseStream);
}