How do you use CsvWriter to output csv data to a string

55 views
Skip to first unread message

Oni

unread,
Apr 22, 2008, 1:25:10 AM4/22/08
to CSVChat
Have a datatable full of records which need to be rendered as csv and
the result of that needs to go to a string. So have tried with below
sample code (and various iterations) to get the desired result.
However no joy as I get an empty string every time. Appreciate if
anyone can shed light on this or point out the blindingly obvious

MemoryStream foMS = new MemoryStream();
DataStreams.Csv.CsvWriter foCSVWrite = new
DataStreams.Csv.CsvWriter(foMS, ',', Encoding.ASCII);
StreamReader foCsvRead = new StreamReader(foMS, Encoding.ASCII);

foCSVWrite.Write("hello");
string fsMystr = foCsvRead.ReadToEnd();

foCSVWrite.Close();

shriop

unread,
Apr 22, 2008, 8:50:35 AM4/22/08
to CSVChat
As far as I know, you can not write and read from the same
MemoryStream. You have to grab the contents as a byte array and create
a new MemoryStream to read from. You also need to call Flush on the
CsvWriter, which will in turn call Flush on the internal StreamWriter
which buffers by default. I tried just adding the Flush call to your
sample code and I still got the empty string. The code below does
output a string.

using (MemoryStream foMS = new MemoryStream())
using (CsvWriter foCSVWrite = new CsvWriter(foMS, ',',
Encoding.ASCII))
{
foCSVWrite.Write("hello");
foCSVWrite.Flush();

using (MemoryStream foMSRead = new MemoryStream(foMS.ToArray()))
using (StreamReader foCsvRead = new StreamReader(foMSRead,
Encoding.ASCII))
{
string fsMystr = foCsvRead.ReadToEnd();
Console.WriteLine(fsMystr);
Console.ReadLine();
}
}

Bruce Dunwiddie

shriop

unread,
Apr 22, 2008, 8:55:39 AM4/22/08
to CSVChat
Actually, it looks like the missing piece is to set the Position back
to 0. You still have to call Flush also. The code below does work.

using (MemoryStream foMS = new MemoryStream())
using (CsvWriter foCSVWrite = new CsvWriter(foMS, ',',
Encoding.ASCII))
using (StreamReader foCsvRead = new StreamReader(foMS,
Encoding.ASCII))
{
foCSVWrite.Write("hello");
foCSVWrite.Flush();
foMS.Position = 0;

string fsMystr = foCsvRead.ReadToEnd();
Console.WriteLine(fsMystr);
Console.ReadLine();
}

Bruce Dunwiddie

> > foCSVWrite.Close();- Hide quoted text -
>
> - Show quoted text -
Reply all
Reply to author
Forward
0 new messages