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.
CodePudding user response:
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 FileStream
as well as a BinaryWriter
and write the bytes to the BinaryWriter
// Create File Stream,
// Create BinaryWriter So We Can Write A PDF.
using (FileStream fs = new FileStream(tempPath, FileMode.Create))
using (BinaryWriter binaryWriter = new BinaryWriter(fs, Encoding.UTF8))
{
binaryWriter.Write(bytes);
}
you can then return the tempPath
to the caller and read the bytes when required.
If you need to display the PDF in the browser you will need to attach application/pdf
to the ContentType in the Response Headers
so the browser knows how to handle the request.