开发者

C# download file from the web

开发者 https://www.devze.com 2023-02-22 22:36 出处:网络
Is there a way to make the following function work via proxy? public T[] ReadStream(System.IO.TextReader reader);

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?


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


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);
}


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

精彩评论

暂无评论...
验证码 换一张
取 消