StringHelper.cs
public static string CreateCSVTextFile<T>(List<T> data) { var properties = typeof(T).GetProperties(); var result = new StringBuilder(); var header = properties.Select(x => x.Name).Select(z => StringToCSVCell(z)); var headerline = string.Join(",", header); result.AppendLine(headerline); foreach (var row in data) { var values = properties.Select(p => p.GetValue(row, null)) .Select(v => StringToCSVCell(Convert.ToString(v))); var line = string.Join(",", values); result.AppendLine(line); } return result.ToString(); } private static string StringToCSVCell(string str) { bool mustQuote = (str.Contains(",") || str.Contains("\"") || str.Contains("\r") || str.Contains("\n")); if (mustQuote) { StringBuilder sb = new StringBuilder(); sb.Append("\""); foreach (char nextChar in str) { sb.Append(nextChar); if (nextChar == '"') sb.Append("\""); } sb.Append("\""); return sb.ToString(); } return str; }
DownloadController.cs (API Controller)
[HttpGet] [Route("down")] public HttpResponseMessage down(int id) { HttpResponseMessage result = null; try { using (var repo = new SomeRepository()) { var some= repo.All.ToList(); ; if (some!= null) { result = new HttpResponseMessage(HttpStatusCode.OK); var csvString = StringHelper.CreateCSVTextFile<Some>(risk); byte[] byteArray = Encoding.ASCII.GetBytes(csvString); MemoryStream stream = new MemoryStream(byteArray); result.Content = new StreamContent(stream); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = string.Format("some_{0}.csv", id); } } } catch (Exception e) { var errorResponse = new HttpResponseMessage(HttpStatusCode.InternalServerError); errorResponse.Content = new StringContent(e.Message); return errorResponse; } return result; } }
