【问题标题】:Creating a dialog for saving a csv file with C# and asp.net使用 C# 和 asp.net 创建用于保存 csv 文件的对话框
【发布时间】:2017-09-07 11:18:14
【问题描述】:

在我的代码中,我有一个 asp 中继器,我希望允许用户将数据从中导出到 csv 文件。导出到 csv 可以正常工作,但是当我希望显示一个对话框供用户选择保存位置时,什么也没有发生。我经历了几种不同的解决方案,这些解决方案显然有效,但是当我在我的代码中运行它们时,什么也没有发生,我不知道为什么。这是我目前的代码:

protected void exportCSV_Click(object sender, EventArgs e)
{
    try
    {
        string FilePath = Server.MapPath("~") + "\\test.csv";
        StringBuilder columnbind = new StringBuilder();
        foreach (Control item in rpt_bookings.Items)
        {
            Literal row1 = (Literal)item.FindControl("ltl_bookingemail");
            Literal row2 = (Literal)item.FindControl("ltl_bookingphone");
            Literal row3 = (Literal)item.FindControl("ltl_bookingcost");
            string fullRow = row1.Text.ToString() + "," + row2.Text.ToString() + "," + row3.Text.ToString();
            columnbind.Append(fullRow);
            columnbind.Append("\r\n");
        }
        //// Creates the file on server
        File.WriteAllText(FilePath, columnbind.ToString());
        string FileName = "test.csv";
        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
        response.ClearContent();
        response.Clear();
        response.ContentType = "text/csv";
        response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
        response.TransmitFile(FilePath);
        response.Flush();
        response.End();

        //// Deletes the file on server
        File.Delete(FilePath);

        //response.End();
        lblmsg.Text = "";
    }
    catch (Exception ex)
    {
        Console.Write(ex);
        Debug.Write(ex);
        lblmsg.Text = ex.Message;
        lblmsg.Style.Add("color", "#c73939");
    }
}

csv 已正确创建,但响应没有任何反应。代码执行了,但屏幕上什么也没有出现。根据类似的其他几个问题,这就是解决方案。

【问题讨论】:

  • 尝试在标题的文件名部分添加转义引号; response.AddHeader("Content-Disposition", "attachment; filename=\"" + FileName + "\";");
  • @DanielPark 这并没有改变什么

标签: c# asp.net csv httpresponse


【解决方案1】:

尝试以下更改:

response.ContentType = "application/octet-stream";
response.AppendHeader("Content-Disposition","attachment; filename=" + Filename + ";");
response.TransmitFile( FilePath );
response.End();

不要删除下一行中的文件,而是删除 finally 块中的文件:

catch (Exception ex)
{
    [..]
}
finally
{
    File.Delete(FilePath);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多