Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 允许用户通过Response.WriteFile()从我的站点下载_C#_Asp.net - Fatal编程技术网

C# 允许用户通过Response.WriteFile()从我的站点下载

C# 允许用户通过Response.WriteFile()从我的站点下载,c#,asp.net,C#,Asp.net,我正试图通过点击我的网站上的链接以编程方式下载一个文件(它是我的web服务器上的一个.doc文件)。这是我的代码: string File = Server.MapPath(@"filename.doc"); string FileName = "filename.doc"; if (System.IO.File.Exists(FileName)) { FileInfo fileInfo = new FileInfo(File); long Length = fileInfo

我正试图通过点击我的网站上的链接以编程方式下载一个文件(它是我的web服务器上的一个.doc文件)。这是我的代码:

string File = Server.MapPath(@"filename.doc");
string FileName = "filename.doc";

if (System.IO.File.Exists(FileName))
{

    FileInfo fileInfo = new FileInfo(File);
    long Length = fileInfo.Length;


    Response.ContentType = "Application/msword";
    Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
    Response.AddHeader("Content-Length", Length.ToString());
    Response.WriteFile(fileInfo.FullName);
}
这在buttonclick事件处理程序中。好的,我可以对文件路径/文件名代码做一些修改,使其更整洁,但是当单击按钮时,页面会刷新。在localhost上,这段代码运行良好,允许我下载文件ok。我做错了什么


谢谢

哦,您不应该在按钮单击事件处理程序中执行此操作。我建议将整个过程移动到HTTP处理程序(
.ashx
)并使用
Response.Redirect
或任何其他重定向方法将用户带到该页面


如果仍要在事件处理程序中执行此操作。请确保执行
响应。在写出文件后结束
调用。

您可以使用一个download.aspx页面来代替按钮单击事件处理程序


然后,此页面可以在页面加载事件中包含您的代码。还添加Response.Clear();在您的回复之前。ContentType=“Application/msword”;行,并添加Response.End();在您的Response.WriteFile(fileInfo.FullName)之后;行。

尝试稍微修改的版本:

string File = Server.MapPath(@"filename.doc");
string FileName = "filename.doc";

if (System.IO.File.Exists(FileName))
{

    FileInfo fileInfo = new FileInfo(File);


    Response.Clear();
    Response.ContentType = "Application/msword";
    Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
    Response.WriteFile(fileInfo.FullName);
    Response.End();
}

愚蠢的问题:“filename.doc”是否存在于服务器上的同一位置(相对于应用程序根)?正是我要说的:response.Clear before和response.end after。