Original: C # self-compacting class method for exporting database tables to CSV compressed files
When exporting a large number of CSV data, often large size, the use of C # comes with the compression class, you can easily implement this function, and compression ratio is very high, this method in my open Source Tool Datapie has been tested in practice. My previous Blog "full-featured, efficient first-class free open source database import and Export tools (C # Development, support SQL Server, SQLite, access three kinds of database), monthly take this processing data 5G above the tool's full source, there is the need for students to see."
In. NET 4.5, you can easily create a zip file that first requires the introduction of System.IO.Compression.dll, System.IO.Compression.FileSystem.dll two files. Where the Ziparchive class represents some compressed files that use the Zip file format. The Ziparchiveentry class represents a single ziparchive. Ziparchive typically contain one or more ziparchiveentry instances.
The main code for the export of CSV file compression in Datapie is as follows:
usingSystem;usingSystem.Linq;usingSystem.Text;usingSystem.IO.Compression;usingSystem.Data;usingSystem.Diagnostics;usingSystem.IO;namespacedatapie.core{ Public classDbtozip { Public Static intDatareadertozip (String zipfilename, IDataReader Reader,stringtablename) {Stopwatch Watch=stopwatch.startnew (); Watch. Start (); using(FileStream fsoutput =NewFileStream (Zipfilename, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { using(Ziparchive archive =Newziparchive (Fsoutput, ziparchivemode.update)) {Ziparchiveentry Readmeentry= Archive. Createentry (tablename +". csv"); using(StreamWriter writer =NewStreamWriter (Readmeentry.open (), Encoding.UTF8)) { for(inti =0; I < reader. FieldCount; i++) { if(I >0) writer. Write (','); Writer. Write (reader. GetName (i)); } writer. Write (Environment.NewLine); while(reader. Read ()) { for(inti =0; I < reader. FieldCount; i++) { if(I >0) writer. Write (','); String v=Reader[i]. ToString (); if(V.contains (',') || V.contains ('\ n') || V.contains ('\ r') || V.contains ('"') {writer. Write ('"'); Writer. Write (V.replace ("\"","\"\"")); Writer. Write ('"'); } Else{writer. Write (v); }} writer. Write (Environment.NewLine); }}}} watch. Stop (); returnConvert.ToInt32 (watch. Elapsedmilliseconds/ +); } }}