473,799 Members | 3,740 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

yoda
291 Contributor
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 17338
yoda
291 Contributor
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 Recognized Expert Moderator Contributor
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
52692
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 using streams, datadoc, xmlreader, etc with no success. I need to convert it directly to a string or via a stream, but not in a file. Here's some sample code that gives me the bad format. I'll post the good format below that give me rowsets rather...
5
3349
by: dickster | last post by:
Ok I have a class called Product ============================================== Code: Product.vb ============================================== Imports System.Xml.Serialization <XmlRootAttribute(ElementName:="product", :="x")> _ Public Class product Public _product_name As String End Class ==============================================
3
5702
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 would be appreciated. Thanks Rod
2
1820
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
31442
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 an arraylist and I don't know how. Can anyone help?
2
2135
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? I have a sub that calls a function: Dim bByte() As Byte bByte = ws.SQLGetUserDemographics()
2
8557
by: noopathan | last post by:
Hi experts , I have an excel file in the below format --------------------------------------------------------------------- CodeID CodeName Market Name Date -------------------------------------------------------------------- 1 Sample1 Market1 22/2/2004 -------------------------------------------------------------------- 2 Sample2 Market2 22/2/2003
3
1977
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 dataset?
4
5669
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) On each FileSystemItem Element, make two child nodes, one with the file name, one with the file size. ie. <filesystemitems> <filesystemitem>
0
2880
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 me out with this. Thanks. DataTable dtMaterials = new DataTable(); StringWriter swMaterials = new StringWriter(); swMaterials = null; string strMaterials = string.Empty;
0
9541
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10485
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10252
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10231
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10027
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9073
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5463
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4141
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3759
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.