从字符串压缩和压缩文件 [英] Compress and zip file from string

查看:78
本文介绍了从字符串压缩和压缩文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的csv,需要通过电子邮件发送,该文件必须压缩,否则可能会达到smtp服务器的最大限制.我正在基于数据库查询在内存中生成csv.

I have a big csv that I need to send by email, the file must be compressed otherwise it might hit the max limit of the smtp server. I'm generating the csv in memory based on a database query.

我正在尝试使用此问题的答案

I was trying to use the answer on this question C# Compress and zip csv from stream. but it didn't work(possibly because of the different c# version, I'm using .net core 2.2)

最终的csv是一个字符串,然后我将其转换为Stream并将其传递给答案的扩展名.

The final csv is a string which I then convert to a Stream and pass it to the extensions of the answer the question.

我从答案中使用的代码(略有改编):

The code I'm using from the answer(slight adapted):

    {
        public string FileName { get; set; }
        public Stream FileStream { get; set; }
    }

    public static class ZipArchiveExtensions
    {

        public static Stream GenerateStreamFromString(string s)
        {
            var stream = new MemoryStream();
            var writer = new StreamWriter(stream);
            writer.Write(s);
            writer.Flush();
            stream.Position = 0;
            return stream;
        }

        public static Stream Compress(this FileModel file) => Compress(new FileModel[] { file });
        public static Stream Compress(this IEnumerable<FileModel> files)
        {
            if (files.Any())
            {
                var ms = new MemoryStream();
                var archive = new ZipArchive(ms, ZipArchiveMode.Create, false);
                foreach (var file in files)
                {
                    var entry = archive.add(file);
                }
                ms.Position = 0;
                return ms;
            }
            return null;
        }

        private static ZipArchiveEntry add(this ZipArchive archive, FileModel file)
        {
            var entry = archive.CreateEntry(file.FileName, CompressionLevel.Fastest);
            using (var stream = entry.Open())
            {
                file.FileStream.CopyTo(stream);
                // stream.Position = 0;
                stream.Close();
            }
            return entry;
        }
    }

我如何使用代码:

                var stream = ZipArchiveExtensions.GenerateStreamFromString(csvStr);
                var file = new FileModel { FileName = reportName + ".csv", FileStream = stream };
                var compressedFile = file.Compress();

                var attachment = new Attachment(compressedFile, reportName + ".zip");
                await this._emailService.SendMessageAsync(reportRequest.MailTo, reportName, null, new[] { attachment });

由于某些原因,电子邮件上的结果zip文件无效.

For some reason the result zip file on the email is invalid.

推荐答案

必须放置 ZipArchive 对象,以将其内容正确写入其基础流.另外,您必须将 leaveOpen 标志设置为true,以便在处置档案时,不会关闭 compressedFile .

The ZipArchive object has to be disposed to properly write its content to its underlying stream. Additionally, you have to set the leaveOpen flag to true so upon disposing the archive, the compressedFile will not be closed.

public static Stream Compress(this IEnumerable<FileModel> files)
{
    if (files.Any())
    {
        var ms = new MemoryStream();
        using (var archive = new ZipArchive(ms, ZipArchiveMode.Create, leaveOpen: true))
        {
            foreach (var file in files)
            {
                var entry = archive.add(file);
            }
        }        
        ms.Position = 0;
        return ms;
    }
    return null;
}

这篇关于从字符串压缩和压缩文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆