ASP.NET下从Server端下载文件到Client端C#

private void DownLoadFile(string file)
{
try
{
string fileName = new FileInfo(file).Name;

Stream stm = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read);
Response.Clear();
Response.ContentType = "application/octet-stream";
fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8).Replace("+", "%20");
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.AppendHeader("Content-length", stm.Length.ToString());

BinaryReader br = new BinaryReader(stm);

byte[] bytes;

for (Int64 x = 0; x < (br.BaseStream.Length / 51200 + 1); x++)
{
bytes = br.ReadBytes(51200);
Response.BinaryWrite(bytes);
Response.Flush();
}

Response.Close();
stm.Close();

}
catch(Exception ex)
{
StreamWriter sw = null;
Encoding sjisEnc = Encoding.GetEncoding("Shift_JIS");
sw = new StreamWriter(@"C:logBatchJoLog.txt", true, sjisEnc);
sw.Write(ex);
sw.Close();
}
}

Love it, and you live without it
原文地址:https://www.cnblogs.com/tomclock/p/6307049.html