public void DownloadFile(string dowloadFilePath)
{
Response.Clear();
Response.Buffer = true;
Response.Expires = 0;
System.IO.FileStream _streamReader = System.IO.File.OpenRead(dowloadFilePath);
int _count = 0;
byte[] _bytes = null;
string _strFilename = "";
_strFilename = dowloadFilePath.Substring(dowloadFilePath.LastIndexOf("\\") + 1);
Response.ContentType = "octet-stream";
Response.AddHeader("content-disposition", "attachment; filename=" + HttpUtility.UrlEncode(_strFilename));
try
{
int maxLengthPerPackage = 1024 * 1024;
long FileLength = _streamReader.Length;
if (FileLength <= maxLengthPerPackage)
{
_bytes = new byte[FileLength];
_streamReader.Read(_bytes, 0, (int)(FileLength)); // 读取文件内容
Response.BinaryWrite(_bytes);
Response.Flush();
}
else
{
//当文件大于1M时,分段读文件,以防死机
for (int i = 0; i <= FileLength / maxLengthPerPackage; i++)
{
if (FileLength - (i * maxLengthPerPackage) > maxLengthPerPackage)
_bytes = new byte[maxLengthPerPackage];
else
_bytes = new byte[FileLength % maxLengthPerPackage];
int canReadLength = _streamReader.Read(_bytes, 0, _bytes.Length); // 读取文件内容
_count += canReadLength;
Response.BinaryWrite(_bytes);
Response.Flush();
}
}
}
//分段读文件,以防死机
finally
{
if (_streamReader != null)
{
_streamReader.Close();
//System.IO.File.Delete(dowloadFilePath); //delete output tempary file
}
}
Response.End();
}
C# DownloadFile
最新推荐文章于 2024-06-20 18:43:11 发布