I have a razor page that lists files availableble in a server directory. I intend to download a file when i click on the associated
Download ActionLink. I am getting error
HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
.
Additional trace details include :
Module IIS Web Core
Notification MapRequestHandler
Handler StaticFile
Error Code 0x80070002
Requested URL http:
Physical Path C:\Users\tshumae\source\repos\MySolution\MyProject\FileProcess\Downloads\C:\Users\tshumae\source\repos\PureFlexGateway\MIHR_SYSTEM\Downloads\log4net-cheat-sheet.pdf
This is how im downloading the files :
DownloadFiles.cs
<pre> public List<DownLoadFileInformation> GetBatches()
{
List<DownLoadFileInformation> lstFiles = new List<DownLoadFileInformation>();
string realPath = @"C:\Users\tshumae\source\repos\MySolution\MyProject\Downloads";
IEnumerable<string> fileList = Directory.EnumerateFiles(realPath);
if (System.IO.Directory.Exists(realPath))
{
int i = 0;
foreach (string file in fileList)
{
FileInfo f = new FileInfo(file);
string separator = "\\";
var sep = separator.ToString();
StringBuilder sb = new StringBuilder(realPath);
var filepath = sb.Append(sep);
lstFiles.Add(new DownLoadFileInformation()
{
FileId = i + 1,
FileName = Path.GetFileName(file),
FileSize = f.Length,
FilePath = filepath + Path.GetFileName(file),
});
i = i + 1;
}
}
return lstFiles.ToList();
}
FileProcessController.cs
This view returns a listing of the files :
public ActionResult Index()
{
var filesCollection = obj.GetBatches();
return View(filesCollection);
}
And this method downloads a file :
public FileResult Download(string URL)
{
string CurrentFileUrl = Convert.ToString(URL);
var filesCol = obj.GetBatches();
string CurrentFileUrll = (from fls in filesCol
where fls.FilePath == CurrentFileUrl
select fls.FilePath).FirstOrDefault();
byte[] fileBytes = System.IO.File.ReadAllBytes(CurrentFileUrll);
string CurrentFileName = (from fls in filesCol
where fls.FilePath == CurrentFileUrl
select fls.FileName).FirstOrDefault();
string contentType = string.Empty;
if (CurrentFileName.Contains(".pdf"))
{
contentType = "application/pdf";
}
else if (CurrentFileName.Contains(".docx"))
{
contentType = "application/docx";
}
return File(fileBytes, contentType,CurrentFileName);
}
What I have tried:
I have searched around and suggestions point that i have to pass the filename and extension
separately in my view here :
<pre> <td>
@Html.ActionLink("Download", "Download", new { id = item.FilePath })
</td>
but im not entirely sure how to achieve the same and i do think its a lot of work? Is there a better way to download a file in my context or alternatively how can i pass in filename and extension separately.