这是个通过http下载网络URL所指向的资源的实例,写的比较简陋,还请见谅。
主要用到的控件:SaveFileDialog,ProcessBar等。
主要用到了输入输出流的知识以及多线程的知识。
(关于“如何:对 Windows 窗体控件进行线程安全调用”的问题,欢迎访问http://msdn.microsoft.com/query/dev11.query?appId=Dev11IDEF1&l=ZH-CN&k=k(EHInvalidOperation.WinForms.IllegalCrossThreadCall);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.0);k(DevLang-csharp)&rd=true)
我这里使用了“CheckForIllegalCrossThreadCalls = false;”的方法(等于完全忽视了线程安全~不过省事啊~)
代码很简单,直接贴下来就好了:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace ReadStream
{
public partial class Download : Form
{
public Download()
{
InitializeComponent();
//多线程省些事
CheckForIllegalCrossThreadCalls = false;
}
private int processCount=0;
private void button1_Click(object sender, EventArgs e)
{
string urlStr = textBox1.Text;
string saveNameStr = textBox2.Text;
if (textBox1.Text.Equals("") || textBox2.Text.Equals(""))
{
MessageBox.Show("请填写输入信息");
}
else
{
new Thread(new ThreadStart(OnDownLoad)).Start();
}
}
public void OnDownLoad()
{
button1.Text = "下载中";
button1.Enabled = false;
string showText = DownloadFile(textBox1.Text, textBox2.Text);
MessageBox.Show(showText);
button1.Text = "下载";
button1.Enabled = true;
progressBar1.Value = 0;
processCount = 0;
}
/// <summary>
/// 下载文件
/// </summary>
/// <param name="URL">下载文件地址</param>
/// <param name="Filename">下载后的存放地址</param>
public String DownloadFile(string URL, string filename)
{
try
{
System.Net.HttpWebRequest myRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
System.Net.HttpWebResponse myResponse = (System.Net.HttpWebResponse)myRequest.GetResponse();
long totalBytes = myResponse.ContentLength;
if (myResponse.ContentLength != 0)
{
System.IO.Stream st = myResponse.GetResponseStream();
System.IO.Stream so = new System.IO.FileStream(filename,System.IO.FileMode.Create);
long totalDownloadedByte = 0;
byte[] by = new byte[1024];
int restSize = st.Read(by, 0, (int)by.Length);
while (restSize > 0)
{
totalDownloadedByte = restSize + totalDownloadedByte;
so.Write(by, 0, restSize);
restSize = st.Read(by, 0, (int)by.Length);
//处理process
processCount = (int)(100 * totalDownloadedByte / totalBytes);
progressBar1.Value = processCount;
}
so.Close();
st.Close();
return "成功";
}
else
{
return "网络资源不存在";
}
}
catch (System.Exception e)
{
return "下载文件失败!" + e.ToString();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
textBox2.Text = saveFileDialog1.FileName;
}
}
private void Download_Load(object sender, EventArgs e)
{
textBox2.Enabled = false;
}
}
}
程序界面很简洁:
项目实例已经上传,欢迎下载~