Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MemoryStream to string[]

Tags:

c#

I read the content of a CSV file from a zip file in memory(the requirment is not to write to disk) into the MemoryStream. and use to following code to get the human readable string

 string  result = Encoding.ASCII.GetString(memoryStream.ToArray());

However, we would like the result to be a string[] to map each row in the CSV file.

Is there a way to handle this automatically?

Thanks

like image 426
Stratford Avatar asked Mar 01 '13 17:03

Stratford


People also ask

What is MemoryStream?

MemoryStream encapsulates data stored as an unsigned byte array. The encapsulated data is directly accessible in memory. Memory streams can reduce the need for temporary buffers and files in an application. The current position of a stream is the position at which the next read or write operation takes place.


1 Answers

Firstly, there's no need to call ToArray on the memory stream. Just use a StreamReader, and call ReadLine() repeatedly:

memoryStream.Position = 0; // Rewind!
List<string> rows = new List<string>();
// Are you *sure* you want ASCII?
using (var reader = new StreamReader(memoryStream, Encoding.ASCII))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        rows.Add(line);
    }
}
like image 96
Jon Skeet Avatar answered Sep 22 '22 16:09

Jon Skeet