您可以尝试以下ASP。NET/C#代码段:
internal static void Download(string FileName)
{
HttpResponse _response = HttpContext.Current.Response;
FileStream _fileStream;
byte[] _arrContentBytes;
try
{
// clear response obj
_response.Clear();
// clear content of response obj
_response.ClearContent();
// clear response headers
_response.ClearHeaders();
// enable response buffer
_response.Buffer = true;
// specify response content
_response.ContentType = ContentType;
_response.StatusCode = 206;
_response.StatusDescription = "Partial Content";
// create FileStream: IMPORTANT - specify FileAccess.Read
_fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
// Bytes array size= (int)_fs.Length;
_arrContentBytes = new byte[(int)_fileStream.Length];
// read file into bytes array
_fileStream.Read(_arrContentBytes, 0, (int)_fileStream.Length);
// add response header
_response.AddHeader("content-disposition", "attachment;filename=" + FileName);
// ACTUAL PROCEDURE: use BinaryWrite to download file
_response.BinaryWrite(_arrContentBytes);
// ALTERNATIVE: TransmitFile
//_response.TransmitFile(filePath);
// close FileStream
_fileStream.Flush();
_fileStream.Close();
_response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch { }
finally
{
_fileStream = null;
_arrContentBytes = null;
}
}
为了获得根文件夹和完整路径,您可以使用
Server.MapPath
如您的原始解决方案或以下行中所示,以获得更好的性能:
// get the root dir; fast
string _root = AppDomain.CurrentDomain.BaseDirectory;
此解决方案已在实际web应用程序中测试/实现(
http://taxiom.com/Manual_Payday.aspx
)-有关演示,请参阅页面右上角的“下载”按钮。希望这能有所帮助。