代码下载.dat文件

时间:2017-08-07 02:54:14

标签: c# asp.net

我尝试使用Response.Redirect为用户编写代码以下载.dat文件。 但是,它总是向我显示这个错误。

The page you are requesting cannot be served because of the extension 
configuration. If the page is a script, add a handler. If the file should be
downloaded, add a MIME map.

我的Response.redirect示例代码

Response.Redirect(filepath, false);

我没有错。另外,我可以使用此代码下载.xlsx文件。

感谢您的帮助。

这是对下载无响应的更新代码 已编辑的代码

string fpath = Server.MapPath("data") + "\\" + filename + ".dat";
 if (File.Exists(fpath))
{
File.Delete(fpath);
}
StreamWriter swExtLogFile = new StreamWriter(fpath, true);
try
{
int i;
foreach (DataRow row in tbl.Rows)
{
object[] array = row.ItemArray;
for (i = 0; i < array.Length - 1; i++)
{
swExtLogFile.Write(array[i].ToString());
}
swExtLogFile.WriteLine(array[i].ToString());
}
swExtLogFile.Close();
swExtLogFile.Dispose();
FileInfo fInfo = new FileInfo(fpath);
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Length", fInfo.Length.ToString());
Response.AppendHeader("content-disposition", 
string.Format("attachment;filename={0}", fInfo.Name));
 Response.Flush();
Response.TransmitFile(fInfo.FullName);
HttpContext.Current.ApplicationInstance.CompleteRequest();    

1 个答案:

答案 0 :(得分:0)

试试这个

您不必执行MIME映射。

private void dwnldFile(string filepath)
{
    FileInfo fInfo = new FileInfo(filepath);
    Response.Clear();
    Response.ContentType = "application/octet-stream";
    Response.AddHeader("Content-Length", fInfo.Length.ToString);
    Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", fInfo.Name));
    Response.Flush();
    Response.TransmitFile(fInfo.FullName)
    Response.End();
}