0

I have an Asp.net core MVC project in visual studio. I have added a folder called Download to the project and added the file "ReadMe.txt" into that folder. I'm trying to enable the user to download the file. In my view I have:

@Html.ActionLink("Readme.txt", "ReadMe", "Download")

This calls the ReadMe action inside the DownloadController. However, I have been struggling for the past hour to write the action method to return the file.

I think something like this should do it but the IDE does not recognise Server and I cannot find an import to resolve it. I've tried using System.Web and it does not work.

public FileResult ReadMe()
{
    string filename = "ReadMe_2.1.txt";
    string serverpath = Server.MapPath("~/Download/");
    string filepath = serverpath + filename;

    return File(filepath, System.Net.Mime.MediaTypeNames.Application.Octet, filename);
}

Any suggestions?

Steve W
  • 1,108
  • 3
  • 13
  • 35
  • `Server` does not exist in core-mvc. Refer [this answer](https://stackoverflow.com/questions/35237863/download-file-using-mvc-core) for one option –  Apr 17 '18 at 09:57
  • Awesome. That was exactly what I needed. Sorry I couldn't find it before. – Steve W Apr 17 '18 at 10:08

2 Answers2

0

Thanks to Stephen Muecke for directing me to this similar problem: Download File using MVC Core

As I struggled to find the answer myself, I also provide the code here that solved my issue in hope that it may help anybody else in similar circumstances:

public FileResult ReadMe()
{
    var fileName = $"ReadMe_2.1.txt";
    var filepath = $"Download/{fileName}";
    byte[] fileBytes = System.IO.File.ReadAllBytes(filepath);
    return File(fileBytes, "application/txt", fileName);
}

All credit to https://stackoverflow.com/users/5528313/vague

Steve W
  • 1,108
  • 3
  • 13
  • 35
-1

View

@foreach (var item in ViewData.Model)
    {
        @Html.ActionImage("Home", "DownloadFile", new { filename = item }, "~/Images/Standard/downloadIcon.png")
    }

Controller

public ActionResult DownloadFile(string filename)
    {
        if (Path.GetExtension(filename) == ".pdf")
        {
            string fullPath = Path.Combine(Server.MapPath("~/Images/ArticleOfAssociations"), filename);
            return File(fullPath, "ArticleOfAssociations/pdf");
        }
        else
        {
            return new HttpStatusCodeResult(System.Net.HttpStatusCode.Forbidden);
        }
    }
Bombebak
  • 114
  • 2
  • 11
  • Read the question (there is no `Server.MapPath()` in asp.net-core-mvc!) –  Apr 17 '18 at 09:56