Search code examples
c#.netproxydownloadtextreader

C# download file from the web


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?


Solution

  • 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.
        }
    }