I have a String variable (in C#) that contain the full path of PDF file on my server (like that \"~/doc/help.pdf\").
I want that in click on button, this file will down
I would suggest the following to be placed into your button click event code.
This will provide the user with a popup to download the file. I've tested it thoroughly and use it in production code.
void btnDownloadFile_Click(object sender, EventArgs e)
{
string strLocalFilePath = "~/doc/help.pdf";
string fileName = "help.pdf";
Response.Clear();
Stream iStream = null;
const int bufferSize = 64 * 1024;
byte[] buffer = new Byte[bufferSize];
int length;
long dataToRead;
try
{
iStream = new FileStream(strLocalFilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
dataToRead = iStream.Length;
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
while (dataToRead > 0)
{
if (Response.IsClientConnected)
{
length = iStream.Read(buffer, 0, bufferSize);
Response.OutputStream.Write(buffer, 0, length);
Response.Flush();
buffer = new byte[bufferSize];
dataToRead = dataToRead - length;
}
else
{
//prevent infinate loop on disconnect
dataToRead = -1;
}
}
}
catch (Exception ex)
{
//Your exception handling here
}
finally
{
if (iStream != null)
{
iStream.Close();
}
Response.Close();
}
}