static void Main(string[] args)
{
FileStream fs = new FileStream("1.rar", FileMode.Open);
BinaryReader dr = new BinaryReader(fs);
byte [] bs=new byte[(int)fs.Length ];
dr.Read(bs,0,bs.Length);
dr.Close();
HttpListener listen = new HttpListener();
Console.WriteLine("The Connect sucessed ");
listen.Prefixes.Add("http://127.0.0.1:80/My/1.rar/");
listen.Start();
while(true)
{
HttpListenerContext context = listen.GetContext();
context.Response.AddHeader("Content-disposition", "attachment:filename='1.rar'");
context.Response.AppendHeader("Content-Lengh", bs.Length.ToString());
context.Response.AddHeader("Content-Transfer-Encoding", "binary");
context.Response.ContentType = "Application/octet-stream";
try
{
Console.WriteLine("Sending...........");
context.Response.OutputStream.Write(bs, 0, bs.Length);
context.Response.OutputStream.Flush();
context.Response.OutputStream.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message.ToString());
Console.ReadLine();
}
}
//这段代码执行时,在浏览器地址栏里输入:http://127.0.0.1/My/1.rar
//迅雷能检测到文件的大小,也能实现下载。但是抛出异常:
//在前缀“http://127.0.0.1:80/My/1.rar/”上侦听失败,因为它与计算机上的现有注册冲突。
//有时还不稳定,不能实现下载。
//望各位指教一二,如果有更好的代码能实现如上的下载方法,望赐教。