C#winform实现下载文件的功能

1.首先新建一个窗体,添加一个Button

2.在Button的点击事件中添加代码:

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

FileMode是操作系统打开文件的方式的枚举,它有6个重载方式:

Append,Create,CreateNew,Open,OpenOrCreate,Truncate


猜你喜欢

转载自blog.csdn.net/clearloveq/article/details/80902262