C# 从网上下载文件

标签 c# .net proxy download textreader

有没有办法通过代理实现以下功能?

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

我希望能够代理 reader 实例,以便它可以在读取尝试时从网络下载文件并将其缓存在某处。

或者为此目的可能有一些默认设置?

最佳答案

使用 WebClient.DownloadFile。如果需要代理,可以设置 WebClient 对象的 Proxy 属性。

这是一个例子:

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

您还可以使用 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.
    }
}

关于C# 从网上下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5601061/

相关文章:

c# - 如何从 WPF 中通过 SaveFileDialog 保存 BitmapImage?

c# - 是否可以在 PCL 中使用 .AsParallel 扩展方法?

c# - 如何写入主 exe .config 用户设置部分?

nginx 代理传递子路径未重定向

Python 请求库在代理后面无法处理 HTTPS URL 的重定向

c# - 如何在 ASP.Net 中的单个页面中显示多个 HTML 内容?

c# - UWP 中的 Process.Start

c# - 使用构造函数从 dapper 获取非原始类型的对象

nginx - oauth2-proxy 身份验证在 kubernetes 集群上调用缓慢,并带有 nginx 入口的身份验证注释

c# - 为什么 Microsoft F# 指南不建议从 C# 使用的代码中返回元组?