问题
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)
回答1:
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.
回答2:
You will need to install the NuGet package DotNetZip.
This will work for you:
public ActionResult DownloadFile()
{
string string1 = "value1, value2, value3, value4";
string string2 = "value10, value20, value30, value40";
List<String> files = new List<String>();
files.Add(string1);
files.Add(string2);
byte[] buffer = CompressStringToFile("myfile.zip", files);
return File(buffer, "application/zip");
}
private byte[] CompressStringToFile(string fileName, List<string> content)
{
byte[] result = null;
int count = 0;
using (var ms = new MemoryStream())
{
using (var s = new ZipOutputStream(ms))
{
foreach (string str in content)
{
s.PutNextEntry(String.Format("entry{0}.txt", count++));
byte[] buffer = Encoding.UTF8.GetBytes(str);
s.Write(buffer, 0, buffer.Length);
}
}
result = ms.ToArray();
}
return result;
}
来源:https://stackoverflow.com/questions/24571773/how-do-i-zip-multiple-files-using-gzipstream-in-c-sharp