FileStreamResult与FileContentResult

时间:2014-04-16 11:16:14

标签: c# .net memorystream

我有一个方法

public virtual FileContentResult DownloadUserFileTemplate()
{
    var dataRow = new DataRow { RowItems = new List<string> { "Name", "Email", "Roles" } };            
    var templateFileInMemoryStream = documentHandler.CsvDocumentCreator.Create(new List<DataRow> { dataRow }); //CsvDocumentCreator.Create method create stream object in using block and returns it.
    return File(templateFileInMemoryStream.ToArray(), "text/csv", "UserImportSheet.csv");
}

我们知道FileStreamResult也存在。所以,如果我将上面的代码重构为:

public virtual FileStreamResult DownloadUserFileTemplate()
{          
    var dataRow = new DataRow { RowItems = new List<string> { "Name", "Email", "Roles" } };
    var templateFileInMemoryStream = documentHandler.CsvDocumentCreator.Create(new List<DataRow> { dataRow });
    return File(templateFileInMemoryStream, "text/csv", "UserImportSheet.csv");
}

当我尝试使用上面的文件下载文件时,它会抛出Stream已经关闭的异常。在return语句之后的某处发生异常,因为上面的方法不会抛出任何异常。有什么想法吗?

这是我的CsvDocumentCreator.Create()方法:

 public MemoryStream Create(IList<DataRow> rows)
            {
                rows.IsNotNull("rows");

                var builder = new StringBuilder();

                foreach (var row in rows)
                {
                    foreach (var rowItem in row.RowItems)
                    {
                        builder.Append(MakeValueCsvFriendly(rowItem)).Append(",");
                    }

                    builder.Remove(builder.Length - 1, 1).AppendLine();
                }

                return GenerateStream(builder.ToString());
            }



private static MemoryStream GenerateStream(string value)
    {
        using (var stream = new MemoryStream())
        {
            using (var writer = new StreamWriter(stream))
            {
                writer.Write(value);
                return stream;
            }
        }
    }

0 个答案:

没有答案