将服务器上的文件通过HttpWebRequest下载到本地

外网地址需要先映射。

string path="";    path=@"http://192.168.1.1/P2Foundation/Images/logo.gif";

            Uri downUri = new Uri(path);
            //建立一个WEB请求,返回HttpWebRequest对象           
            HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(downUri);
            //设置接收对象的范围为0-10000000字节。
            hwr.AddRange(0, 10000000);
            //流对象使用完后自动关闭
            using (Stream stream = hwr.GetResponse().GetResponseStream())
            {
                //文件流,流信息读到文件流中,读完关闭
                using (FileStream fs = File.Create(@"C:\Users\Evan\Desktop\test\755.jpg"))
                {
                    //建立字节组,并设置它的大小是多少字节
                    byte[] bytes = new byte[102400];
                    int n = 1;
                    while (n > 0)
                    {
                        //一次从流中读多少字节,并把值赋给N,当读完后,N为0,并退出循环
                        n = stream.Read(bytes, 0, 10240);
                        fs.Write(bytes, 0, n); //将指定字节的流信息写入文件流中
                    }
                }
            }

转自https://www.cnblogs.com/lori/archive/2011/09/09/2172761.html

posted @ 2018-04-02 11:47  Evan_Zhang  阅读(488)  评论(0)    收藏  举报