如何使用C#生成带有dat文件和txt文件的zip

时间:2016-04-20 14:15:50

标签: c# algorithm download zip

我需要创建一个文件txt和一个扩展名为dat的文件。之后我想将这些文件压缩成zip文件并下载。

我的问题是我不想在下载之前保存文件。那么,我可以在不在服务器上创建文件的情况下创建和下载zip吗?

2 个答案:

答案 0 :(得分:0)

我使用 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;
        }
    }
}

答案 1 :(得分:-1)

我假设您正在使用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);