473,394 Members | 1,737 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Possible? Convert DataTable to MemoryStream then to CSV then ZIP it.

yoda
291 100+
Hi everyone I'm fairly new to the C# programming language and was wonder if it is possible to Convert a DataTable to a MemoryStream then output that into a CSV file and then Zip that file.

Also note I know how to get to the CSV File part but don't know how to take that file and Zip it without creating it on a clients computer and reading it in and Zipping it.

But this Zip file must be created and zipped on the webserver and then Zip file can be downloaded as an attachment.

A little more context to the situation. What I'm basically doing is creating a CSV file from a select statement from a database but only when the user clicks on a button on the ASP page.

Here's the code I use to just make a csv file.

Note: In this code there is no MemoryStream, but I do know how to create a CSV that way.
Expand|Select|Wrap|Line Numbers
  1.  
  2. try
  3.             {
  4.                 GetSqlData(); //get sql data for the csv.
  5.  
  6.                 HttpContext context = HttpContext.Current;
  7.                 context.Response.Clear();
  8.  
  9.                 foreach (DataColumn column in FullDT.Columns)
  10.                 {
  11.                     context.Response.Write(column.ColumnName.ToString() + ",");
  12.                 }
  13.                 context.Response.Write(Environment.NewLine);
  14.  
  15.                 foreach (DataRow row in FullDT.Rows)
  16.                 {
  17.                     for (int i = 0; i < row.ItemArray.Length; i++)
  18.                     {
  19.                         string rowText = row.ItemArray[i].ToString();
  20.                         if (rowText.Contains(","))
  21.                         {
  22.                             rowText = rowText.Replace(",", "/");
  23.                         }
  24.  
  25.                         context.Response.Write(rowText + ",");
  26.                     }
  27.                     context.Response.Write(Environment.NewLine);
  28.                 }
  29.  
  30.                 context.Response.ContentType = "text/csv";
  31.                 context.Response.AppendHeader("Content-Disposition", "attachment; filename="+ OutputFileName +".csv");
  32.                 context.Response.End();
  33.             }
  34.             catch (Exception ex)
  35.             {
  36.                 Debug.WriteLine("Can Not Generate CSV File");
  37.                 throw ex;
  38.             }
Is this even possible with out the help of an additional library outside of C#?

Thanks,

Yoda.
Feb 9 '12 #1
2 17160
yoda
291 100+
So I wasn't able to use do this without the aid of a external library because I was using .NET 2.0. But with the external SharpZipLib Library I was able to create this code fairly easily.

Basic Idea is to place the datatable into a memory stream like so:
Expand|Select|Wrap|Line Numbers
  1. MemoryStream mem = new MemoryStream(); // create a memory stream to hold the datatable.
  2.             StreamWriter sw = new StreamWriter(mem); // write the datatable to the memory stream.
  3.  
  4.             //Loop through the columns and rows and add a comma to the end for the csv.
  5.             foreach (DataColumn column in Datatbl.Columns)
  6.             {
  7.                 sw.Write(column.ColumnName.ToString() + ",");
  8.             }
  9.  
  10.             sw.WriteLine();
  11.  
  12.             foreach (DataRow row in Datatbl.Rows)
  13.             {
  14.                 for (int i = 0; i < row.ItemArray.Length; i++)
  15.                 {
  16.                     string rowText = row.ItemArray[i].ToString();
  17.                     if (rowText.Contains(","))
  18.                     {
  19.                         rowText = rowText.Replace(",", "/");
  20.                     }
  21.  
  22.                     sw.Write(rowText + ",");
  23.                 }
  24.                 sw.WriteLine();
  25.             }
  26.             sw.Flush();
  27.             return mem; 
  28.  
And then use the External Library to help you place the file or files into the zip file for download.

Expand|Select|Wrap|Line Numbers
  1. Stream fs = null; // create the streams so they can be closed if an expection is caught.
  2.             ZipOutputStream zipOutputStream = null;
  3.  
  4.             try
  5.             {
  6.                 Response.ContentType = "application/zip";
  7.                 // If the browser is receiving a mangled zipfile, IIS Compression may cause this problem. Some members have found that
  8.                 //    Response.ContentType = "application/octet-stream"     has solved this. May be specific to Internet Explorer.
  9.  
  10.                 Response.AppendHeader("content-disposition", "attachment; filename=\"" + OutputFileName + ".zip\"");
  11.                 Response.CacheControl = "Private";
  12.                 Response.Cache.SetExpires(DateTime.Now.AddMinutes(3)); // or put a timestamp in the filename in the content-disposition
  13.  
  14.  
  15.  
  16.                 zipOutputStream = new ZipOutputStream(Response.OutputStream);
  17.                 zipOutputStream.SetLevel(3); //0-9, 9 being the highest level of compression
  18.  
  19.                 fs = (Stream)GetStream();    // or any suitable inputstream
  20.                 fs.Position = 0;
  21.  
  22.                 ZipEntry entry = new ZipEntry("" + OutputFileName + ".csv");
  23.                 entry.Size = fs.Length;
  24.                 // Setting the Size provides WinXP built-in extractor compatibility,
  25.                 //  but if not available, you can set zipOutputStream.UseZip64 = UseZip64.Off instead.
  26.  
  27.                 zipOutputStream.PutNextEntry(entry);
  28.  
  29.                 byte[] bytes = new byte[fs.Length];
  30.                 int numBytesToRead = (int)fs.Length;
  31.  
  32.                 while (numBytesToRead > 0)
  33.                 {
  34.                     int n = fs.Read(bytes, 0, 4096);
  35.                     if (n == 0)
  36.                     {
  37.                         break;
  38.                     }
  39.                     zipOutputStream.Write(bytes, 0, n);
  40.                     numBytesToRead -= n;
  41.                     Response.Flush();
  42.                 }
  43.             }
  44.             catch (Exception ex)
  45.             {
  46.                 throw ex;
  47.             }
  48.  
  49.             finally
  50.             {
  51.                 fs.Close();
  52.                 zipOutputStream.Close();
  53.  
  54.                 Response.Flush();
  55.                 Response.End();
  56.             }
  57.  
I used the SharpZipLib site as a reference: http://wiki.sharpdevelop.net/SharpZi...hment_in_IIS_2

As well as used the Stream.Read() on MSDN to help me figure out how to read the stream and put it into the zip file.
Feb 15 '12 #2
PsychoCoder
465 Expert Mod 256MB
Thanks for sharing your solution. If someone comes along with a similar issue there's a possible solution available.
Feb 15 '12 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: jk | last post by:
I'm having trouble converting a datatable into xml, with resonse.write to aspx. I'm basically converting vb code that saved a recordset into a stream into c#, but the format is wrong. I've tried...
5
by: dickster | last post by:
Ok I have a class called Product ============================================== Code: Product.vb ============================================== Imports System.Xml.Serialization...
3
by: Rodusa | last post by:
I am looking for an example of how to save a DataTable into Base64 and vice-versa. I tried using Convert.ToBase64String(), but it says that it cannot convert DataTable to byte. Any help or pointing...
2
by: JL | last post by:
Hi all, I want to sort the rows in dataTable and the order of rows is permanent change, is this possible in dataTable? Thanks a lot.
2
by: Steve | last post by:
I have a very simple datatable of 1 column which I retrieve from a database, call it 'data'. Dim data As Data.DataTable data = myobject.mymethod(parameter) I want to now turn this 'data' into...
2
by: SQLScott | last post by:
For some reason I am drawing a blank on this, so I would be extremely greatful if someone could help me out. I am trying to get a MemoryStream out of a Byte array. How do I get it back out? ...
2
by: noopathan | last post by:
Hi experts , I have an excel file in the below format --------------------------------------------------------------------- CodeID CodeName Market Name Date...
3
by: Tom | last post by:
I have a dataTable being returned from my datalayet, I need to convert it to a dataSet so I can do some data manipulation to it prior to populating my datagrid. How can I convert the datatable to a...
4
by: | last post by:
Hi all, I want to create a method that does the following: 1) Programmatically instantiate a new XmlDataSource control 2) For each file in a named directory, make a "FileSystemItem" element 3)...
0
by: =?Utf-8?B?cm9uZSBtYXRpYXM=?= | last post by:
I have the same task to do but everytime I tried to parse my code I get a null value returned after executing "dtMaterials.WriteXml(swMaterials);". I am using the following code: Hope you can hep...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.