在Windows Mobile中利用WebRequest下载文件并获得响应头的信息信息

来源:互联网 发布:如何练好英语知乎 编辑:程序博客网 时间:2024/05/19 17:57


using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.IO;using System.Net;namespace DownloadFile{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private void btnGet_Click(object sender, EventArgs e)        {            Uri u = new Uri(txtUrl.Text);            Download(u, System.Environment.GetFolderPath(Environment.SpecialFolder.Personal)/* 此处获得我的文档的路径 */);         }        private void Download(Uri address, string localPath)        {            string filename = "test.txt";            WebRequest request = WebRequest.Create(address);            //perform the GET request            WebResponse response = request.GetResponse();            //get stream containing received data            Stream s = response.GetResponseStream();            //open filestream for the output file            FileStream fs = new FileStream(Path.Combine(localPath, filename), FileMode.Create, FileAccess.Write);            //copy until all data is read 标准的缓存读取格式            byte[] buffer = new byte[1024];            int bytesRead = s.Read(buffer, 0, buffer.Length);            while (bytesRead > 0)            {                fs.Write(buffer, 0, bytesRead);                bytesRead = s.Read(buffer, 0, buffer.Length);            }            //close both streams            fs.Close();            s.Close();            response.Close();            MessageBox.Show("ok");        }        private void btnHead_Click(object sender, EventArgs e)        {                      System.Net.HttpWebRequest hwr = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(txtUrl.Text);            hwr.Method = "HEAD";            System.Net.WebResponse response = hwr.GetResponse();            string[] str = response.Headers.AllKeys;            foreach (string temp in str)            {                this.listBox1.Items.Add("key="+temp+" length="+response.Headers[temp]);            }        }        private void menuItem1_Click(object sender, EventArgs e)        {            Application.Exit();        }    }}


0 0
原创粉丝点击