从服务器取图片

//url服务器存储图片的路径

public static Stream Load(string url)
        {
            HttpWebRequest request = null;
            HttpWebResponse response = null;

            // Request page protected by forms authentication.
            // This request may get a 302 to login page
            request = (HttpWebRequest)WebRequest.Create(url);
            request.AllowAutoRedirect = false;
            if (CookieCache != null)
                request.AddCookie(CookieCache);

            response = (HttpWebResponse)request.GetResponse();
            if (response.StatusCode == HttpStatusCode.Found)
            {
                // must re-login
                throw new ApplicationException("会话超时,请重新登录!");
                
            }
               
            if (response.StatusCode == HttpStatusCode.OK)
            {
                return response.GetResponseStream();
            }

            // error to reach here
            return null;
        }

两种处理Stream的方法

url服务器的路径

filePath存储到本地的路径

private bool LoadFile(string url, string filePath)
        {
            try
            {
               using (var output = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite, FileShare.Read, 8192, FileOptions.None))
                using (var input = Barm.Utility.Storage.Load(url))
                {

                   //将服务器的流拷到本地
                    input.CopyTo(output);
                    input.Close();
                }
                return true;
            }
            catch (Exception)
            {
                MessageBox.Show("下载出错!");
                return false;
            }
        }

 

private bool LoadFile(string url, string filePath)
        {
            try
            {
                FileStream fs = new FileStream(filePath, System.IO.FileMode.Create);
                System.IO.Stream ns = Barm.Utility.Storage.Load(url);//获得接收流
                byte[] nbytes;//接收缓冲区
                int nreadsize;//接收字节数
                nbytes = new byte[512];
                nreadsize = 0;

                //从服务器读写流
                nreadsize = ns.Read(nbytes, 0, 512);
                while (nreadsize > 0)
                {
                    fs.Write(nbytes, 0, nreadsize);
                    nreadsize = ns.Read(nbytes, 0, 512);
                }
                fs.Close();
                ns.Close();
            }
            catch (Exception)
            {
                MessageBox.Show("下载出错!");
                return false;
            }
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值