I have created multiple csv files using datatable and want to zip all those file into one single zip file. Which is i'm doing all at dynamically.
I tried following code
List<string> filestream = GenerateCSVfiles(dataSets);
//Generate CSV files
public List<string> GenerateCSVfiles(List<DataSet> dataSets)
{
List<string> filestream = new List<string>();
StringBuilder result = null;
foreach (DataSet dataSet in dataSets)
{
result = new StringBuilder();
System.Data.DataTable dataTable = dataSet.Tables[0];
foreach (DataColumn colm in dataTable.Columns)
{
result.Append(colm.ColumnName+",");
}
result.Append("\n");
//create csv file
foreach (DataRow row in dataTable.Rows)
{
for (int i = 0; i < dataTable.Columns.Count; i++)
{
result.Append(row[i].ToString());
result.Append(i == dataTable.Columns.Count - 1 ? "\n" : ",");
}
}
filestream.Add(result.ToString());
}
return filestream;
}
Now in List<filestream>
I have all 2 file data want to create 2 different .csv
files and create one temp.gz
file dynamically How can I do this ?
On ActionResult
method I tried following code to generate .zip file but it is corrupted
return File(CompressStringToFile("temp.gz", filestream), System.Net.Mime.MediaTypeNames.Application.Zip, "temp.gz");
// zip file generation code
public byte[] CompressStringToFile(string fileName, List<string> filestream)
{
MemoryStream f2 = new MemoryStream();
FileStream fs = new FileStream();
GZipStream gz = new GZipStream(f2, CompressionMode.Compress, false);
foreach (string oStr in filestream)
{
byte[] b = GetBytes(oStr);
gz.Write(b, 0, b.Length);
}
return f2.ToArray();
}
Correct me to generate .zip file. (with inside 2 .csv files)
You can't do this with a GZipStream
. You'll need a 3rd party library. Probably the best one out there is SharpZipLib. I've used this on projects in the past, and it's very easy to use. Plus it's been around for a while so should be pretty stable and bug-free.