In one of my asp.net web applications I need to hide the location of a pdf file being served to the users.
Thus, I am writing a method that retrieves its binary con
This snippet includes the code for reading in the file from a file path, and extracting out the file name:
private void DownloadFile(string path)
{
using (var file = System.IO.File.Open(path, FileMode.Open))
{
var buffer = new byte[file.Length];
file.Read(buffer, 0, (int)file.Length);
var fileName = GetFileName(path);
WriteFileToOutputStream(fileName, buffer);
}
}
private string GetFileName(string path)
{
var fileNameSplit = path.Split('\\');
var fileNameSplitLength = fileNameSplit.Length;
var fileName = fileNameSplit[fileNameSplitLength - 1].Split('.')[0];
return fileName;
}
private void WriteFileToOutputStream(string fileName, byte[] buffer)
{
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition",
$"attachment; filename\"{fileName}.pdf");
Response.OutputStream.Write(buffer, 0, buffer.Length);
Response.OutputStream.Close();
Response.Flush();
Response.End();
}