Windows Mobile Web方式下载文件

      以前所使用的下载文件,都是通过webService + WSE进行的,而WebService是以XML为载体的,这样,在下载文件的时候,必然包含着一些没有的结构信息,从而也就增加了实际要下载的文件的大小,对于移动设备而言,网络流量是非常宝贵的,为了节约流量,所以写了一个通过WebRequest和WebResponse完成网络文件下载的方法,改方法的好处是流量比较小,但缺点是,要被现在的文件必须放到Internet网络上,这样便对文件的安全性和下载用户的可控性带来一定的影响,下面是实现的代码

        /// <summary>
        /// 从指定的URL以二进制方式现在文件
        /// </summary>
        /// <param name="fileURL">文件所存放的Internet地址</param>
        /// <returns>成功下载后,文件在本地存放的位置,如果下载失败,则返回""</returns>
        private string DownLoadFile(string fileURL)
        {
            StreamReader rdr = null;
            FileStream wrtr = null;
            string localFileName = string.Empty;
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(fileURL);
                req.Method = "GET";

                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                long len = resp.ContentLength;
                Stream respStream = resp.GetResponseStream();
                localFileName = @"/Program Files/" + fileURL.Substring(fileURL.LastIndexOf("/") + 1);

                 wrtr = new FileStream(localFileName, FileMode.Create);

                byte[] inData = new byte[4096];

                int bytesRead = respStream.Read(inData, 0, inData.Length);
                while (bytesRead > 0)
                {
                    wrtr.Write(inData, 0, bytesRead);
                    bytesRead = respStream.Read(inData, 0, inData.Length);
                }
                //判断下在是否成功
                System.IO.FileInfo fi = new FileInfo(localFileName);
                if (fi.Length != len)
                    localFileName = string.Empty;
                fi = null;
              
            }
            catch (Exception ep)
            {
                MessageBox.Show(ep.Message);
            }
            finally
            {
                if(rdr != null)
                    rdr.Close();
                if(wrtr != null)
                    wrtr.Close();
                Cursor.Current = Cursors.Default;
            }
            return localFileName;
        }

 

你可能感兴趣的:(Windows Mobile)