如何使用 C# 生成带有 dat 文件的 zip 和 txt 文件
本文关键字:文件 zip txt dat 何使用 | 更新日期: 2024-10-30 13:39:34
我需要创建一个文件txt和一个扩展名为dat的文件。之后,我想将这些文件压缩成zip文件并下载。
我的问题是我不想在下载前保存文件。那么,我可以在不创建服务器上的文件的情况下创建和下载zip吗?
我使用了MemoryStream。您可以在下面找到代码:
public ZipOutputStream CreateZip(MemoryStream memoryStreamControlFile, MemoryStream memoryStreamDataFile)
{
using (var outputMemStream = new MemoryStream())
{
using (var zipStream = new ZipOutputStream(baseOutputStream))
{
zipStream.SetLevel(3); // 0-9, 9 being the highest level of compression
byte[] bytes = null;
// .dat
var nameFileData = CreateFileName("dat");
var newEntry = new ZipEntry(nameFileData) { DateTime = DateTime.Now };
zipStream.PutNextEntry(newEntry);
bytes = memoryStreamDataFile.ToArray();
var inStream = new MemoryStream(bytes);
StreamUtils.Copy(inStream, zipStream, new byte[4096]);
inStream.Close();
zipStream.CloseEntry();
// .suc
var nameFileControl = CreateFileName("suc");
newEntry = new ZipEntry(nameFileControl) { DateTime = DateTime.Now };
zipStream.PutNextEntry(newEntry);
bytes = memoryStreamControlFile.ToArray();
inStream = new MemoryStream(bytes);
StreamUtils.Copy(inStream, zipStream, new byte[4096]);
inStream.Close();
zipStream.CloseEntry();
// .zip
zipStream.IsStreamOwner = false;
zipStream.Close();
outputMemStream.Position = 0;
return zipStream;
}
}
}
我假设您正在使用 ASP.Net?
您可以将文件内容(流等)放在一个字节数组中,然后在响应中将其直接输出给用户,例如:
string fileType = "...zip...";
byte[] fileContent = <your file content> as byte[];
int fileSize = 1000;
string fileName = "filename.zip";
Response.AddHeader("Content-Disposition", "attachment;filename='"" + fileName + "'"");
Response.ContentType = fileType;
Response.OutputStream.Write(fileContent, 0, fileSize);