2014-02-24 73 views
-2
<%@ WebHandler Language="C#" Class="dlde" %> 

using System; 
using System.Web; 

public class dlde : IHttpHandler { 

public void ProcessRequest (HttpContext context) { 
    var fileName = @"D:\Error.txt"; 
    var r = context.Response; 
    r.AddHeader("Content-Disposition", "attachment; filename=" + fileName); 
    r.ContentType = "text/plain"; 
    r.WriteFile(context.Server.MapPath(fileName)); 
} 

public bool IsReusable { 
    get { 
     return false; 
    } 
} 

}如何将txt文件从服务器系统下载到客户端?

我想从指定目录下载从服务器系统的.txt文件...我试图与此代码,但我得到的错误,无效的虚拟path..How得到文件从服务器系统..please帮我...

+0

显示确切的异常及其出现的位置。文件是否存在? – CodeCaster

+2

'@D:\ Error.txt'不是有效的虚拟路径。 – Sambasiva

+0

在我的评论中,我问了几个问题,而不仅仅是那个问题,但无论如何,那么不要'Server.MapPath()'它,因为它已经是一个绝对路径。 – CodeCaster

回答

0

使用"WebClient "

 string remoteUri = "http://Yoursite.com/file.txt"; 
    string fileName = @"D:\"; 
     WebClient myWebClient = new WebClient(); 
     myWebClient.DownloadFile(remoteUri, fileName); 

MSDN学习的命名空间试试这个

0
string fName = @"D:\Error.txt"; 

System.IO.FileStream fs = System.IO.File.Open(fName, System.IO.FileMode.Open); 
byte[] btFile = new byte[fs.Length]; 
fs.Read(btFile, 0, Convert.ToInt32(fs.Length)); 
fs.Close(); 

context.Response.Clear(); 
context.Response.ClearHeaders(); 
context.Response.AddHeader("Content-disposition", "attachment; 
      filename=" + HttpUtility.UrlEncode(fname, System.Text.Encoding.UTF8)); 
context.Response.ContentType = "text/plain"; 
context.Response.BinaryWrite(btFile);   
相关问题