参考:
1. 用VS2008建立一个Windows应用程序:DownloadFileDemo
源代码如下:
1) FileTransformation.cs(该类包含了一个下载文件的方法)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
namespace DownloadFileDemo
{
class FileTransformation
{
//被下载的文件地址,绝对路径
private string webServerUri = "";
//本地端用于保存下载的数据的文件全路径
private string localFilePath = "";
public FileTransformation(string webServerUri, string localFilePath)
{
this.webServerUri = webServerUri;
this.localFilePath = localFilePath;
}
public int DownloadFile()
{
try
{
WebRequest wr = WebRequest.Create(webServerUri);
}
catch (WebException exp)
{
return 1;
}
try
{
//create a new WebClient instance
WebClient client = new WebClient();
client.DownloadFile(webServerUri, localFilePath);
return 0;
}
catch (WebException exp)
{
return 2;
}
}
}
}
Form1.cs
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.Net;
using System.IO;
using System.Threading;
namespace DownloadFileDemo
{
public partial class Form1 : Form
{
//define delegate
private delegate void SetTextCallBack();
OpenFileDialog ofDialog = new OpenFileDialog();
public Form1()
{
InitializeComponent();
}
private void InvokeStartDownload()
{
//initiate delegate
SetTextCallBack stcb = new SetTextCallBack(StartDownload);
Invoke(stcb);
}
private void StartDownload()
{
//Server URL
string fullServerUrl = txtSrcAddress.Text;
//Server Path
//string webServerUrl = fullServerUrl.Substring(0, fullServerUrl.LastIndexOf('/'));
//Local file name
string localFileName = fullServerUrl.Substring(fullServerUrl.LastIndexOf('/') + 1, fullServerUrl.Length - fullServerUrl.LastIndexOf('/') - 1);
//Local file full path
string localFullFilePath = txtTarAddress.Text + '\\' + localFileName;
FileTransformation ft = new FileTransformation(fullServerUrl, localFullFilePath);
int result = ft.DownloadFile();
if (result == 1)
{
lblMsg.Text = "WebRequest实例化失败!";
lblMsg.Visible = true;
}
else if(result == 2)
{
lblMsg.Text = "文件下载失败!";
lblMsg.Visible = true;
}
else if (result == 0)
{
lblMsg.Text = "文件下载成功!";
lblMsg.Visible = true;
}
}
private void BtnStart_Click(object sender, EventArgs e)
{
Thread th = new Thread(new ThreadStart(InvokeStartDownload));
th.Start();
}
private void BtnBrowse_Click(object sender, EventArgs e)
{
ofDialog.Title = "选择文件";
ofDialog.Filter = "All files(*.*)|*.*";
if (ofDialog.ShowDialog() == DialogResult.OK)
{
txtTarAddress.Text = ofDialog.FileName;
}
}
}
}