c# creating file using memorystream instead of textwriter

tmcallaghan picture tmcallaghan · Apr 23, 2009 · Viewed 65.6k times · Source

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.

Answer

Peter Lillevold picture Peter Lillevold · Apr 23, 2009

You could do:

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

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