WCS
WCS

Reputation: 99

Aspnet core 3 -- How to return a text or csv file created as a string builder from a controller?

From a data table, I have generated a text file that I want to export as a .txt or .csv file using a controller action return. In aspx I was able to use:

 MeetingListTxt = stringBuilder.ToString();
            base.Response.Clear();
            base.Response.AddHeader("content-disposition", "attachment;filename=MeetingList.csv");
            base.Response.Charset = "";
            base.Response.ContentType = "application/text";
            base.Response.Output.Write(stringBuilder.ToString());
            base.Response.Flush();
            base.Response.End();

The result was a text file that the user could save to his hard drive.

How can this be done with Aspnet core 3?

Upvotes: 0

Views: 2140

Answers (1)

Brando Zhang
Brando Zhang

Reputation: 27997

As far as I know, in asp.net core we could use FileResult to generate the response which download the text file.

The FileResult will automatically provide the proper Content-Disposition header to attachment.

More details, you could refer to below test demo codes:

        public class Student
        {
            public int Id { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }
        public IActionResult DownloadCommaSeperatedFile()
        {
            List<Student> students = new List<Student>
{
    new Student { Id = 1, FirstName = "Joydip", LastName = "Kanjilal" },
    new Student { Id = 2, FirstName = "Steve", LastName = "Smith" },
    new Student { Id = 3, FirstName = "Anand", LastName = "Narayaswamy"}
};
            try
            {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.AppendLine("Id,FirstName,LastName");
                foreach (var student in students)
                {
                    stringBuilder.AppendLine($"{student.Id},  { student.FirstName},{ student.LastName}");
                }
                return File(Encoding.UTF8.GetBytes
                (stringBuilder.ToString()), "text/csv", "student.csv");
            }
            catch
            {
                return Error();
            }
        }

Result:

enter image description here

Upvotes: 3

Related Questions