ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

c# 下载文件并处理进度

2022-08-20 11:03:25  阅读:203  来源: 互联网

标签:下载 string c# System client 进度 new using WebClient


我们先来个Form

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            System.Net.WebClient client = new System.Net.WebClient();
            byte[] data = client.DownloadData("http://b.hiphotos.baidu.com/zhidao/pic/item/3c6d55fbb2fb4316641d646623a4462309f7d3af.jpg");//一个真正存放数据的地址,一般我们将连接存在数据库中,数据存放在数据服务器上
            //如果网站没有什么限制的话,这样就能得到网站的图片数据了
            string path =Application.StartupPath;
            FileStream fs = new FileStream(path+"\\x.jpg", FileMode.Create);   
            //将byte数组写入文件中
            fs.Write(data,0,data.Length);     
            fs.Close();
        }
    }
}

 这里关键就是 System.Net.WebClient 这个类的用法,官方文档网址:https://docs.microsoft.com/zh-cn/dotnet/api/system.net.webclient?view=net-6.0

比如我们要处理下载进度:

// Sample call : DownLoadFileInBackground4 ("http://www.contoso.com/logs/January.txt");
public static void DownLoadFileInBackground4(string address)
{
    WebClient client = new WebClient();
    Uri uri = new Uri(address);

    // Specify a DownloadFileCompleted handler here...

    // Specify a progress notification handler.
    client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback4);

    client.DownloadFileAsync(uri, "serverdata.txt");
}

private static void DownloadProgressCallback4(object sender, DownloadProgressChangedEventArgs e)
{
    // Displays the operation identifier, and the transfer progress.
    Console.WriteLine("{0}    downloaded {1} of {2} bytes. {3} % complete...",
        (string)e.UserState,
        e.BytesReceived,
        e.TotalBytesToReceive,
        e.ProgressPercentage);
}

 

标签:下载,string,c#,System,client,进度,new,using,WebClient
来源: https://www.cnblogs.com/otkur/p/16607298.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有