FileStream操作写入空文件

时间:2014-11-11 17:44:39

标签: c# asp.net filestream memorystream stringwriter

我有一个正在下载空文件的ASP.Net MVC 4应用程序。我错过了什么?

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public FileStreamResult ICS()
    {
        var memoryStream = new MemoryStream();
        StreamWriter sw = new StreamWriter(memoryStream);
        sw.WriteLine(@"BEGIN:VCALENDAR");
        sw.WriteLine(@"VERSION:2.0");
        sw.WriteLine(@"PRODID:-//www.marudot.com//iCal Event Maker");
        sw.WriteLine(@"BEGIN:VEVENT");
        sw.WriteLine(@"DTSTAMP:20141111T165545Z");
        sw.WriteLine(@"UID:20141111T165545Z-1194755835@marudot.com");
        sw.WriteLine(@"DTSTART;TZID=""America/Chicago"":20141114T080000");
        sw.WriteLine(@"DTEND;TZID=""America/Chicago"":20141114T120000");
        sw.WriteLine(@"SUMMARY:Bobby's Big Bash");
        sw.WriteLine(@"DESCRIPTION:test");
        sw.WriteLine(@"LOCATION:test");
        sw.WriteLine(@"END:VEVENT");
        sw.WriteLine(@"END:VCALENDAR");

        sw.Flush();
        return new FileStreamResult(memoryStream, "text/calendar") { FileDownloadName = "test.ics" };
    }

}

查看:

<h2>Index</h2>
@Html.ActionLink("ical event", "ICS");

点击该链接可下载空的ICS文件。

2 个答案:

答案 0 :(得分:3)

刷新后将MemoryStream对象的Position属性设置为0。

答案 1 :(得分:1)

只是猜测 - 在您下载文件之前,MemoryStream超出了范围。也许看看将内容写入实际文件时会发生什么,然后重新读取该文件。 Path.GetTempFileName();可能对写出临时文件很有用。