Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StreamWriter writing to MemoryStream

Tags:

I was under the impression that when you called Flush() in a StreamWriter object it writes to the underlying stream, but apparently this isn't the case with my code.

Instead of writing to my file it will just write nothing. Any ideas where I'm going wrong?

    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");     } 
like image 952
ediblecode Avatar asked Jun 21 '12 22:06

ediblecode


People also ask

Where does StreamWriter write to?

StreamWriter contains methods to write to a file synchronously (Write and WriteLine) or asynchronously (WriteAsync and WriteLineAsync). File provides static methods to write text to a file such as WriteAllLines and WriteAllText, or to append text to a file such as AppendAllLines, AppendAllText, and AppendText.

What is the difference between StreamWriter and TextWriter?

The StreamWriter class in C# is used for writing characters to a stream. It uses the TextWriter class as a base class and provides the overload methods for writing data into a file. The StreamWriter is mainly used for writing multiple characters of data into a file.

What does a StreamWriter do?

StreamWriter class in C# writes characters to a stream in a specified encoding. StreamWriter. Write() method is responsible for writing text to a stream. StreamWriter class is inherited from TextWriter class that provides methods to write an object to a string, write strings to a file, or to serialize XML.


1 Answers

I believe you need to set Stream.Position = 0. When you write, it advances the position to the end of the stream. When you pass it to File() it starts from the position it is at - the end.

I think the following will work (did not try to compile this):

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

And this way you are not creating any new objects or copying the underlying array.

like image 54
David Thielen Avatar answered Nov 14 '22 12:11

David Thielen