一、在web项目下添加一个“一般处理程序”
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
namespace Silverlightdownload.Web
{
/// <summary>
/// FileDownLoader 的摘要说明
/// </summary>
public class FileDownLoader : IHttpHandler
{
private long ChunkSize = 20;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力
public void ProcessRequest(HttpContext context)
{
// String fileName = context.Request.QueryString["fileName"]; //客户端传来的文件名
//String filePath = context.Server.MapPath("Files/" + fileName); //要下载文件的路径
String filePath = context.Request.QueryString["filePath"];
String fileName = filePath.Substring(filePath.LastIndexOf('/') + 1);
System.IO.Stream iStream = null;
byte[] buffer = new byte[ChunkSize]; // Buffer to read 10K bytes in chunk:
int lengthRead;//读取的大小
long dataLengthToRead;//获得下载文件的总大小
context.Response.Clear();
System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
if (fileInfo.Exists == true)
{
try
{
iStream = System.IO.File.OpenRead(filePath);
dataLengthToRead = iStream.Length;
context.Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
UserLog.WriteErrLog("dataLengthToRead", dataLengthToRead.ToString());
while (dataLengthToRead > 0 && context.Response.IsClientConnected)
{
if (context.Response.IsClientConnected)
{
lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));
context.Response.OutputStream.Write(buffer, 0, lengthRead);
context.Response.Flush();
dataLengthToRead = dataLengthToRead - lengthRead;
UserLog.WriteErrLog("dataLengthToRead", dataLengthToRead.ToString());
}
else {
dataLengthToRead = -1;
}
}
}
catch (Exception ex)
{
UserLog.WriteErrLog("LocalDownloadError", ex.ToString());
return;
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close();
}
}
context.Response.Clear();//注意是clear(),不是close(),close()对空文件报错
context.Response.End();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
二、在页面中添加一个HyperlinkButton控件
<UserControl x:Class="Silverlightdownload.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<HyperlinkButton Name="hyLinkDownLoad" Content="下载文件" HorizontalAlignment="Left" Height="17" Margin="67,83,0,0" VerticalAlignment="Top" Width="73" Click="hyLinkDownLoad_Click" Cursor="Hand"/>
</Grid>
</UserControl>
三、添加点击事件
private void hyLinkDownLoad_Click(object sender, RoutedEventArgs e)
{
string fileName = "C:\\Users\\dell\\Desktop\\ceshi\\hudd1.txt";//要下载的文件名
Uri uri = new Uri("/FileDownLoader.ashx?filePath=" + fileName, UriKind.Relative);
this.hyLinkDownLoad.NavigateUri = uri;
}