There are word files and pdf files stored in a folder without extensions. When we open these files with pdf view or word viewer the corresponding files gets rendered. Now the requirement is to download these files from .net core application on click of the file name.
Below is the code sample:
public IActionResult Download(int Id)
{
var fileDetails = GetFileDetailsById(Id);
string fullpath = Path.Combine(_configuration.GetValue<string>("ServerPath:Documents:FolderPath"), FileNameWithoutExtension);
List<string> lines = new List<string>();
StreamReader reader = new StreamReader(fullpath);
while (!reader.EndOfStream)
{
lines.Add(reader.ReadLine());
}
byte[] dataAsBytes = lines.SelectMany(s => System.Text.Encoding.UTF8.GetBytes(s + Environment.NewLine)).ToArray();
var content = new System.IO.MemoryStream(dataAsBytes);
var contentType = ContentType; // Content ype saved in DB
var downloadFileName = OriginalFileName;// Original File Name saved in DB
return File(content, contentType, downloadFileName);
}
value of "fullpath" would be "\foldername\filename" without extension.
When the application is run, the files are downloaded without extension.
I would need help in downloading files with extension.
Something like this might help point you in the right direction as from the comments it sounds like you're having trouble with downloading a PDF file even with the extension attached.
Use
byte[] bytes = System.IO.File.ReadAllBytes(FilesPath)Once you have done that create a temp file path
string tempPath = Path.Combine(Path.GetTempPath(),$"{DateTimeOffset.UtcNow.ToUnixTimeSeconds()}.pdf");After that create the temp file using
FileStreamas well as aBinaryWriterand write the bytes to theBinaryWriteryou can then return the
tempPathto the caller and read the bytes when required.If you need to display the PDF in the browser you will need to attach
application/pdfto the ContentType in theResponse Headersso the browser knows how to handle the request.