Search code examples
asp.netfilecsvresponse

Responding with a csv file in asp.net


I am trying to make a csv file from a textbox and then send it to the user. This is my code so far:

Response.Clear();
            Response.ContentType = "text/csv";
            Response.AppendHeader("Content-Disposition",
                string.Format("attachment; filename={0}", DateTime.Now));

            Response.Write(TextBox_Data.Text);
            Context.Response.End();

What is sent is an empty xml file, I have never tried responding with a file before and I'm wondering why it does this?

I have also tried the following which did not work:

var writer = File.CreateText("C:\\file.csv");
            writer.WriteLine(TextBox_Data.Text);

            Context.Response.Clear();
            Context.Response.AppendHeader("content-disposition", "attachment; filename=" + DateTime.Now + ".csv");
            Context.Response.ContentType = "text/csv";
            Context.Response.Write("C:\\file.csv");
            Context.Response.Flush();
            Context.Response.End();

Let me know if you have the answer :)


Solution

  • The following code worked for me. You may just be missing a file extension.

    Response.Clear();
    Response.ContentType = "text/csv";
    Response.AppendHeader("Content-Disposition",
                    string.Format("attachment; filename={0}.csv", DateTime.Now));
    Response.Write(TextBox_Data.Text);
    Context.Response.End();