C#MVC-FileStreamResult返回CSV空CSV文件

时间:2019-04-11 15:09:14

标签: c# asp.net-mvc csv filestreamresult

我正在尝试导出带有对象结果的csv。

在我的控制器中:

    [System.Web.Http.HttpGet]
    public FileStreamResult GetCsvExample()
    {

        try
        {

            MemoryStream exampleUsers = new BusinessLogic().Example();
            return File(exampleUsers, MediaTypeEnum.CSV, "Example.csv");
        }
        catch (Exception ex)
        {
            var errorReport =
                new FileStreamResult(new MemoryStream(Encoding.UTF8.GetBytes(ex.Message)), MediaTypeEnum.Text)
                {
                    FileDownloadName = "Error.txt"
                };
            return errorReport;
        }

    }

然后在我的BusinessLogic中

public class BusinessLogic
{
    public MemoryStream Example()
    {
        List<ExampleObject> example= new List<ExampleObject>
        {
            new ExampleObject {Age = 12,City = "Scranton",Name = "joey",State = "PA"},
            new ExampleObject {Age = 22,City = "Tampa",Name = "billy",State = "FL"},
            new ExampleObject {Age = 44,City = "Dallas",Name = "david",State = "TX"},
            new ExampleObject {Age = 90,City = "LA",Name = "susan",State = "CA"},
            new ExampleObject {Age = 3,City = "St Pete",Name = "ann",State = "FL"},
            new ExampleObject {Age = 56,City = "New York",Name = "mike",State = "NY"},
            new ExampleObject {Age = 34,City = "Huston",Name = "derek",State = "TX"},
            new ExampleObject {Age = 67,City = "Atlanta",Name = "brian",State = "GA"},
            new ExampleObject {Age = 96,City = "Anchroage",Name = "jesse",State = "AK"},
            new ExampleObject {Age = 12,City = "Chicago",Name = "jessica",State = "IL"},
        };

        return ListToMemoryStream(example);
    }
}

 private static MemoryStream ListToMemoryStream<T>(IEnumerable<T> parts)
    {
        var csv = new StringBuilder();
        var csvLine = new StringBuilder();

        //Build the header
        PropertyInfo[] partAddPropsProperties = typeof(T).GetProperties();
        foreach (var prop in partAddPropsProperties) csvLine.Append(prop.Name).Append(",");
        csvLine.Remove(csvLine.Length - 1, 1).AppendLine();
        string headerLine = csvLine.ToString().Replace(Environment.NewLine, string.Empty).Trim();
        string[] headers = headerLine.Split(',');
        csv.AppendLine(headerLine);

        //Build lines in order of the header
        foreach (var part in parts)
        {
            var partLine = new StringBuilder();

            foreach (var header in headers)
                partLine.Append("\"" + part.GetType().GetProperty(header)?.GetValue(part, null) + "\"").Append(",");


            partLine.Remove(partLine.Length - 1, 1).AppendLine();
            csv.AppendLine(partLine.ToString().Replace(Environment.NewLine, string.Empty).Trim());
        }
        return GenerateStream(csv.ToString());
    }

    private static MemoryStream GenerateStream(string value)
    {
        var stream = new MemoryStream();
        var writer = new StreamWriter(stream);
        writer.Write(value);
        writer.BaseStream.Seek(0, SeekOrigin.Begin);
        return stream;
    }

在返回MemoryStream之前,我遵循了很多examples saying just to add writer.BaseStream.Seek(0, SeekOrigin.Begin);,但这似乎行不通。它只是返回一个空白CSV文件。

我在编写MemoryStream之前就设置了一个断点,并且可以看到数据正确输入:

  

“姓名,年龄,城市,州\ r \ n \”乔伊\“,\” 12 \“,\”斯克兰顿\“,\” PA \“ \ r \ n \” billy \“,\” 22 \“,\”坦帕\“,\” FL \“ \ r \ n \”大卫\“,\” 44 \“,\”达拉斯\“,\” TX \“ \ r \ n \”苏珊\ “,\” 90 \“,\” LA \“,\” CA \“ \ r \ n \” ann \“,\” 3 \“,\” St   Pete \“,\” FL \“ \ r \ n \” mike \“,\” 56 \“,\”新   York \“,\” NY \“ \ r \ n \” derek \“,\” 34 \“,\” Huston \“,\” TX \“ \ r \ n \” brian \“,\” 67 \ “,\” Atlanta \“,\” GA \“ \ r \ n \” jesse \“,\” 96 \“,\” Anchroage \“,\” AK \“ \ r \ n \” jessica \“, \“ 12 \”,\“芝加哥\”,\“ IL \” \ r \ n“

我不知道这是怎么了。我不想使用CSVWriter。

0 个答案:

没有答案