使用 C# 从 Web 下载文件

WebClient 类使得从 Web 下载文件并将其保存在 C# 中的本地文件中变得非常容易。以下代码显示了单击“下载”按钮时程序如何响应。

代码只是创建一个WebClient对象并调用其DownloadFile方法,将远程文件的 URL 和目标文件的名称传递给它。这就是从 Web 下载文件所需要做的全部工作,至少在简单情况下是这样。(如果您需要穿过防火墙或文件管理器不公开,事情就会变得更加复杂。)

完整代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Net;

namespace howto_download_file
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string filename = Application.StartupPath;
            if (!filename.EndsWith("\\")) filename += "\\";
            txtLocalFile.Text = filename + "howto_download_file.zip";
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            Application.DoEvents();

            try
            {
                // Make a WebClient.
                WebClient web_client = new WebClient();

                // Download the file.
                web_client.DownloadFile(txtRemoteFile.Text, txtLocalFile.Text);

                MessageBox.Show("Done");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Download Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

            this.Cursor = Cursors.Default;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

坐井观老天

您的鼓励是我分享的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值