简体   繁体   English

为什么我无法在asp.net上的服务器上找到要下载的文件?

[英]Why i can not find file on the server for download in asp.net?

I'm beginner in asp.net and want to write simple web application to end user can download any file,write this code for that purpose: 我是asp.net的初学者,想编写简单的Web应用程序以使最终用户可以下载任何文件,并为此编写以下代码:

string filePath = "~/beh/" + query[0].OstFileName;
FileInfo file = new FileInfo(filePath);
if (file.Exists) {

    Response.ContentType = "application/octet-stream";
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + query[0].OstFileName.Trim());
    Response.TransmitFile(Server.MapPath("~/beh/" + query[0].OstFileName.Trim()));
    Response.End();
} else {
    Response.Write("<script>alert('File Not Found 1')</script>");
}

but when run that code i get else block alert,means get File Not Found 1 message,Where is my fault?thanks all. 但是当运行该代码时,我得到其他阻止警报,意味着收到“找不到文件1”消息,这是我的错吗?

Your issue is in the following lines. 您的问题在以下几行中。

string filePath = "~/beh/" + query[0].OstFileName;
FileInfo file = new FileInfo(filePath);

You're giving the FileInfo class a virtual path which the FileInfo cannot map to a local physical path on its own. 您正在为FileInfo类提供一个虚拟路径,该FileInfo无法单独映射到本地物理路径。 You are however correctly mapping the virtual path to the local file path when you call Response.TransmitFile. 但是,在调用Response.TransmitFile时,您已正确地将虚拟路径映射到本地文件路径。

Change your code to the following: 将您的代码更改为以下内容:

string filePath = "~/beh/" + query[0].OstFileName;
FileInfo file - new FileInfo(Server.MapPath(filePath));

See: https://msdn.microsoft.com/en-us/library/ms524632(v=vs.90).aspx 请参阅: https : //msdn.microsoft.com/zh-cn/library/ms524632(v=vs.90).aspx

string filePath = "~/beh/" + query[0].OstFileName; 字符串filePath =“〜/ beh /” +查询[0] .OstFileName;

In this line you specify the path to search for, including the filename. 在此行中,指定要搜索的路径,包括文件名。

The next line you check if this file exists and if so save the file from the query result. 您将在下一行检查此文件是否存在,如果存在,请从查询结果中保存该文件。

However if you check if the file exists before you actually save the file it will never exist. 但是,如果在实际保存文件之前检查文件是否存在,则该文件将永远不存在。

Change the path to read: string filePath = Server.MapPath("~\\beh"). 将路径更改为:string filePath = Server.MapPath(“〜\\ beh”)。

Then add the filename to that once you save the file. 保存文件后,将文件名添加到该文件名。

Hope this makes sense. 希望这是有道理的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM