23

我的印象是,当您调用Flush()StreamWriter 对象时,它会写入底层流,但显然我的代码并非如此。

它不会写入我的文件,而是什么都不写。有什么想法我哪里出错了吗?

    public FileResult DownloadEntries(int id)
    {
        Competition competition = dataService.GetCompetition(id);
        IQueryable<CompetitionEntry> entries = dataService.GetAllCompetitionEntries().Where(e => e.CompetitionId == competition.CompetitionId);

        MemoryStream stream = new MemoryStream();
        StreamWriter csvWriter = new StreamWriter(stream, Encoding.UTF8);

        csvWriter.WriteLine("First name,Second name,E-mail address,Preferred contact number,UserId\r\n");

        foreach (CompetitionEntry entry in entries)
        {
            csvWriter.WriteLine(String.Format("{0},{1},{2},{3},{4}",
                entry.User.FirstName,
                entry.User.LastName,
                entry.User.Email,
                entry.User.PreferredContactNumber,
                entry.User.Id));
        }

        csvWriter.Flush();

        return File(stream, "text/plain", "CompetitionEntries.csv");
    }
4

3 回答 3

29

我相信你需要设置Stream.Position = 0. 当您写入时,它会将位置推进到流的末尾。当你将它传递给File()它时,它从它所在的位置开始 - 结束。

我认为以下将起作用(没有尝试编译):

stream.Position = 0;
return File(stream, "text/plain", "CompetitionEntries.csv");

这样您就不会创建任何新对象或复制底层数组。

于 2012-06-21T22:14:44.920 回答
9

您的 MemoryStream 位于最后。更好的代码是使用MemoryStream(Byte[], Int32, Int32, Boolean)构造函数在同一个缓冲区上创建新的 R/o 内存流。

修剪缓冲区上最简单的读/写:

 return File(new MemoryStream(stream.ToArray());

不复制内部缓冲区的 R/o:

 return File(new MemoryStream(stream.GetBuffer(), 0, (int)stream.Length, false);

注意:注意不要处理通过 File(Stream) 返回的流。否则你会得到某种“ObjectDisposedException”。即,如果您只是将原始流的位置设置为 0 并将 StreamWriter 包装到使用中,您将返回已处理的流。

于 2012-06-21T22:13:59.673 回答
3

在玩这个的过程中,我得到了以下原型:

using System.Web.Mvc;
using NUnit.Framework;

namespace StackOverflowSandbox
{
[TestFixture]
public class FileStreamResultTest
{
    public FileStreamResult DownloadEntries(int id)
    {
        // fake data
        var entries = new[] {new CompetitionEntry { User = new Competitor { FirstName = "Joe", LastName = "Smith", Email = "jsmith@example.com", Id=id.ToString(), PreferredContactNumber = "555-1212"}}};

        using (var stream = new MemoryStream())
        {
            using (var csvWriter = new StreamWriter(stream, Encoding.UTF8))
            {
                csvWriter.WriteLine("First name,Second name,E-mail address,Preferred contact number,UserId\r\n");

                foreach (CompetitionEntry entry in entries)
                {
                    csvWriter.WriteLine(String.Format("{0},{1},{2},{3},{4}",
                                                      entry.User.FirstName,
                                                      entry.User.LastName,
                                                      entry.User.Email,
                                                      entry.User.PreferredContactNumber,
                                                      entry.User.Id));
                }

                csvWriter.Flush();
            }

            return new FileStreamResult(new MemoryStream(stream.ToArray()), "text/plain");
        }
    }

    [Test]
    public void CanRenderTest()
    {
        var fileStreamResult = DownloadEntries(1);
        string results;
        using (var stream = new StreamReader(fileStreamResult.FileStream))
        {
            results = stream.ReadToEnd();
        }
        Assert.IsNotEmpty(results);
    }
}

public class CompetitionEntry
{
    public Competitor User { get; set; }
}

public class Competitor
{
    public string FirstName;
    public string LastName;
    public string Email;
    public string PreferredContactNumber;
    public string Id;
}
}
于 2012-06-21T22:27:31.240 回答