CSVWriter and Stream Problem. Please, Urgent. Thank You.

May 26, 2011 at 7:41 PM

Hello,

Hello,

I am using KBCSV to export data to CSV as follows:

CsvWriter writer = new CsvWriter("C:\\Test.csv");

IEnumerable<Device> devices = _deviceService.FindAvailable();

writer.WriteHeaderRecord("Model", "Serial");
foreach (Device device in devices) {
  writer.WriteDataRecord(
    device.Model,
    device.Serial);
};
writer.Close();

This works fine! But now I need to save it to a Stream. So I created a test:

MemoryStream stream = new MemoryStream();
CsvWriter writer = new CsvWriter(stream);

IEnumerable<Device> devices = _deviceService.FindAvailable();

writer.WriteHeaderRecord("Model", "Serial");
foreach (Device device in devices) {
  writer.WriteDataRecord(
    device.Model,
    device.Serial);
};

// writer.Close();

using (var file = File.Create("C:\\Text.csv")) {
  stream.Position = 0;
  stream.CopyTo(file);
}
In this case the saved file is incomplete.

And if I close the writer then when I try to save the file it says the stream cannot be saved because is closed.

I tried all options I could imagine but I can't find a solution.

Any idea what I might do to solve this?

Thank You,

Miguel

Coordinator
Jun 8, 2011 at 3:40 PM

Hi Miguel,

Call Flush on writer:

writer.Flush();

HTH,
Kent