FileStream action writing empty file

2.7k views Asked by At

I have an ASP.Net MVC 4 app that is downloading an empty file. What am I missing?

Controller:

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:[email protected]");
        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" };
    }

}

View:

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

Clicking the link downloads an empty ICS file.

2

There are 2 answers

0
Andrey M. On BEST ANSWER

Set Position property to 0 for the MemoryStream object after flush.

0
sfuqua On

Just a guess - the MemoryStream is going out of scope before you can download the file. Perhaps see what happens when you write the contents to an actual file, then re-read that file. Path.GetTempFileName(); could be useful for writing out a temporary file.