1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| public class CFilestream : System.Web.UI.Page
{
public void WriteFileToResponse(string strSecureFilePath, string strUserFilename, string strContentType = @"application/octet-stream")
{
byte[] dataBlock = new byte[0x1000];
long fileSize;
int bytesRead;
long totalBytesRead = 0;
try
{
using (var fs = new FileStream(strSecureFilePath,
FileMode.Open, FileAccess.Read, FileShare.Read))
{
fileSize = fs.Length;
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = strContentType;
Response.AddHeader("Content-Disposition", "attachment; filename=" + strUserFilename.Replace(" ", "_"));
Response.AddHeader("Content-Length", fileSize.ToString());
bool bContinue = true;
while (totalBytesRead < fileSize && bContinue)
{
if (!Response.IsClientConnected)
{
bContinue = false;
}
bytesRead = fs.Read(dataBlock, 0, dataBlock.Length);
Response.OutputStream.Write(dataBlock, 0, bytesRead);
Response.Flush();
totalBytesRead += bytesRead;
}
//Response.Close(); si activé problème dans chrome, téléchargement ne se termine pas
//Response.End();
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
} |
Partager