码迷,mamicode.com
首页 > Windows程序 > 详细

C#--简单文件下载器

时间:2015-09-01 13:59:12      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:

 class Program
    {
        static void Main(string[] args)
        {
            //创建一个要下载的路径
            WebRequest req = WebRequest.Create("http://static.cnblogs.com/images/adminlogo.gif");
            //响应图片的信息
            using(WebResponse res = req.GetResponse())
            //拿到图片的流
            using(Stream InStream = res.GetResponseStream())
            //拷贝到本地路径
            using(Stream OutStream = new FileStream(@"C:\Users\Administrator\Desktop\C#OOP练习\2.png",FileMode.Create))
            {
                Copy(InStream, OutStream);
            }
            Console.WriteLine("拷贝完成!");
        }

        //封装Copy方法
        static void Copy(Stream InStream, Stream OutStream, int Size)
        { 
            byte[]bytes = new byte[Size];
            int len = 0;
            while((len = InStream.Read(bytes,0,bytes.Length))>0)
            {
                OutStream.Write(bytes, 0, len);
            }
        }
        //Copy方法重载
        static void Copy(Stream InStream,Stream OutStream)
        {
            Copy(InStream,OutStream,1024*1024);
        }
    }

 CopyTo: 文件拷贝方法

 class Program
    {
        static void Main(string[] args)
        {
            //创建一个要下载的路径
            WebRequest req = WebRequest.Create("http://static.cnblogs.com/images/adminlogo.gif");
            //响应图片的信息
            using(WebResponse res = req.GetResponse())
            //拿到图片的流
            using(Stream InStream = res.GetResponseStream())
            //拷贝到本地路径
            using(Stream OutStream = new FileStream(@"C:\Users\Administrator\Desktop\C#OOP练习\2.png",FileMode.Create))
            {
                InStream.CopyTo(OutStream);
            }
            Console.WriteLine("拷贝完成!");
        }

        //封装Copy方法
        static void Copy(Stream InStream, Stream OutStream, int Size)
        { 
            byte[]bytes = new byte[Size];
            int len = 0;
            while((len = InStream.Read(bytes,0,bytes.Length))>0)
            {
                OutStream.Write(bytes, 0, len);
            }
        }
        //Copy方法重载
        static void Copy(Stream InStream,Stream OutStream)
        {
            Copy(InStream,OutStream,1024*1024);
        }
    }

 

C#--简单文件下载器

标签:

原文地址:http://www.cnblogs.com/phpweige/p/4775433.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!