C# 从服务器asp.net下载文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2009057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:37:44  来源:igfitidea点击:

download file from server asp.net

c#asp.netvisual-studioclient

提问by user175084

I want to download a file from server to a local host.

我想从服务器下载文件到本地主机。

i have a code from the net which should work but is not working

我有一个来自网络的代码,它应该可以工作但无法工作

     protected void Button4_Click(object sender, EventArgs e)
    {
     //To Get the physical Path of the file(test.txt)
    string filepath = Server.MapPath("test.txt");

    // Create New instance of FileInfo class to get the properties of the file being downloaded
   FileInfo myfile = new FileInfo(filepath);

   // Checking if file exists
   if (myfile.Exists)
   {
   // Clear the content of the response
   Response.ClearContent();

// Add the file name and attachment, which will force the open/cancel/save dialog box to show, to the header
Response.AddHeader("Content-Disposition", "attachment; filename=" + myfile.Name);

// Add the file size into the response header
Response.AddHeader("Content-Length", myfile.Length.ToString());

// Set the ContentType
Response.ContentType = ReturnExtension(myfile.Extension.ToLower());

// Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
Response.TransmitFile(myfile.FullName);

// End the response
Response.End();
  }

    }

    private string ReturnExtension(string fileExtension)
    {
        switch (fileExtension)
        {
            case ".htm":
            case ".html":
            case ".log":
                return "text/HTML";
            case ".txt":
                return "text/plain";
            case ".doc":
                return "application/ms-word";
            case ".tiff":
            case ".tif":
                return "image/tiff";
            case ".asf":
                return "video/x-ms-asf";
            case ".avi":
                return "video/avi";
            case ".zip":
                return "application/zip";
            case ".xls":
            case ".csv":
                return "application/vnd.ms-excel";
            case ".gif":
                return "image/gif";
            case ".jpg":
            case "jpeg":
                return "image/jpeg";
            case ".bmp":
                return "image/bmp";
            case ".wav":
                return "audio/wav";
            case ".mp3":
                return "audio/mpeg3";
            case ".mpg":
            case "mpeg":
                return "video/mpeg";
            case ".rtf":
                return "application/rtf";
            case ".asp":
                return "text/asp";
            case ".pdf":
                return "application/pdf";
            case ".fdf":
                return "application/vnd.fdf";
            case ".ppt":
                return "application/mspowerpoint";
            case ".dwg":
                return "image/vnd.dwg";
            case ".msg":
                return "application/msoutlook";
            case ".xml":
            case ".sdxl":
                return "application/xml";
            case ".xdp":
                return "application/vnd.adobe.xdp+xml";
            default:
                return "application/octet-stream";
        }
    }

now when the button is clicked the file should be downloaded from the server to the local host computer... but nothing seems to be happening...

现在当单击按钮时,文件应该从服务器下载到本地主机......但似乎没有发生任何事情......

i have the test.txt on the desktop of the serer... the save file option also does not come on the client side..

我在服务器的桌面上有 test.txt ......保存文件选项也没有出现在客户端..

I publish the files and put it in the inetpub folder of the server and run the GUI from the client side.. everything works except this...

我发布文件并将其放在服务器的 inetpub 文件夹中并从客户端运行 GUI .. 一切正常,除了这个......

any suggestions...please help

任何建议...请帮忙

this program downloads a file if it is present in the inetpub folder.. instead i want to download from any location within the server...

如果 inetpub 文件夹中存在该文件,则该程序会下载该文件。相反,我想从服务器内的任何位置下载...

??

??

采纳答案by user175084

ok so i put a Response.Write after

好的,所以我在后面放了一个 Response.Write

 string filepath = Server.MapPath("test.txt");

and found that file path was pointing to the inetpub folder... so when i put the test.txt in that folder it worked... so the program is right..

并发现文件路径指向 inetpub 文件夹......所以当我把 test.txt 放在那个文件夹中时它工作......所以程序是正确的......

but now if the file is any other location in the server how should i modify the program... i am working on it but any suggestions are welcome

但是现在如果文件是服务器中的任何其他位置,我应该如何修改程序......我正在处理它,但欢迎任何建议

Ok i got the answer for any path too

好的,我也得到了任何路径的答案

i remove the server.mappath and put the full location instead.. dont know why it was giving problems before.. but now it is working...

我删除了 server.mappath 并放置了完整的位置......不知道为什么它之前会出现问题......但现在它正在工作......

回答by STW

You mention that test.txt is on the server's desktop. Is it also located right beside the page you're testing? Try either fully-qualifying the path the to the desktop ("C:\Documents and Settings\JohnDoe\Desktop\test.txt") or copying the file to sit alongside the .aspx page.

您提到 test.txt 在服务器的桌面上。它是否也位于您正在测试的页面旁边?尝试完全限定桌面路径(“C:\Documents and Settings\JohnDoe\Desktop\test.txt”)或复制文件以放在 .aspx 页面旁边。

回答by Swati

Write On Button Click On which u Want to Download Files

写按钮点击你想下载文件

protected void Button1_Click(object sender, EventArgs e)

 {

        string allowedExtensions = ".mp4,.pdf,.m4v,.gif,.jpg,.png,.swf,.css,.htm,.html,.txt";
        // edit this list to allow file types - do not allow sensitive file types like .cs or .config

        string fileName = "Images/apple.jpg";
        string filePath = "";

        //if (Request.QueryString["file"] != null) fileName = Request.QueryString["file"].ToString();
        //if (Request.QueryString["path"] != null) filePath = Request.QueryString["path"].ToString();

        if (fileName != "" && fileName.IndexOf(".") > 0)
        {
            bool extensionAllowed = false;
            // get file extension
            string fileExtension = fileName.Substring(fileName.LastIndexOf('.'), fileName.Length - fileName.LastIndexOf('.'));

            // check that we are allowed to download this file extension
            string[] extensions = allowedExtensions.Split(',');
            for (int a = 0; a < extensions.Length; a++)
            {
                if (extensions[a] == fileExtension)
                {
                    extensionAllowed = true;
                    break;
                }
            }

            if (extensionAllowed)
            {
                // check to see that the file exists 
                if (File.Exists(Server.MapPath(filePath + '/' + fileName)))
                {

                    // for iphones and ipads, this script can cause problems - especially when trying to view videos, so we will redirect to file if on iphone/ipad
                   // if (Request.UserAgent.ToLower().Contains("iphone") || Request.UserAgent.ToLower().Contains("ipad")) { Response.Redirect(filePath + '/' + fileName); }
                    Response.Clear();
                    Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
                    Response.WriteFile(Server.MapPath(filePath + '/' + fileName));
                    Response.End();
                }
                else
                {
                    litMessage.Text = "File could not be found";
                }
            }
            else
            {
                litMessage.Text = "File extension is not allowed";
            }
        }
        else
        {
            litMessage.Text = "Error - no file to download";
        }
    }

回答by George Cristian Boteanu

You can change folder to your location:

您可以将文件夹更改为您的位置:

Directory.SetCurrentDirectory(HttpContext.Current.Server.MapPath("~ your path in here")