views:

7741

answers:

2

I have an application that is currently creating a text file to import into an accounting application. It is using the following code to create the file and write lines to it:

    TextWriter tw = new StreamWriter(ExtractFileName);

    tw.WriteLine("ref\tACCOUNT\tbatch\tDEBIT\tCREDIT\tDesc");

I now need to create multiple extract files and plan on compressing them into a single .zip file using SharpZipLib (#ziplib) and want to change my code to do the text file creation "in memory" and using that to create my zip file. I think I should be creating/using a MemoryStream but can't figure out how to port my existing code.

Thanks.

+16  A: 

You could do:

MemoryStream  memoryStream = new MemoryStream();
TextWriter tw = new StreamWriter(memoryStream);

tw.WriteLine("ref\tACCOUNT\tbatch\tDEBIT\tCREDIT\tDesc");
Peter Lillevold
Perfect, thanks for the quick response. My .zip file is now created.
tmcallaghan
Thats great, glad to be of assistance :)
Peter Lillevold
A: 

I would also suggest that this is a good time to try to decouple parts of your app, so that you can change parts of it in the future. So, a TextWriter is a good abstraction for a writable stream, but consider abstracting your export class also.

E.g. now you want to do it like this:

MemoryStream  memoryStream = new MemoryStream();
TextWriter tw = new StreamWriter(memoryStream);

// tab-delimited export
IExporter exporter = new DelimiterExport(data, tw, "\t"); 
exporter.Export();

so that you can easily change it to:

// csv file
IExporter exporter = new DelimiterExport(data, tw, ",");

or any other implementation:

// excel export
IExporter exporter = new ExcelExport(data, tw);

By providing an independent interface, you will make your life easier later.

(csv export should actually use System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ListSeparator instead of plain comma, but that's not the point)

Groo