gpt4 book ai didi

c# - 使用 GZIP 流和内存流正确压缩 CSV

转载 作者:行者123 更新时间:2023-11-30 22:40:55 39 4
gpt4 key购买 nike

我正在使用 GZIPStream 和 MemoryStream 压缩 CSV 文件,并注意到结果文件有些奇怪。 CSV 似乎没有被正确识别。当文件附加到电子邮件时显示,但保存在 Windows 桌面上时工作正常。

这是处理 gzip 部分的当前片段:

GZipStream gStream = null;
MemoryStream mStream = null;
MemoryStream mStream2 = null;
try
{
if (attachment.Length > 0)
{
mStream = new MemoryStream();

gStream = new GZipStream(mStream, CompressionMode.Compress);
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(attachment.ToString());
gStream.Write(bytes, 0, bytes.Length);
gStream.Close();

mStream2 = new MemoryStream(mStream.ToArray());
Attachment emailAttachement = new Attachment(mStream2, "myGzip.csv.gz", "application/x-Gzip");
mailMessage.Attachments.Add(emailAttachement);
}

}

最佳答案

我能够使用下面的代码进行 gzip 压缩并发送 csv。 GZipStream 在其 Close() 方法被调用之前不会完成写入。当创建 gzipStream 的 using block 完成时会发生这种情况。即使使用 block 完成后流输出也关闭,仍然可以使用 ToArray() 或 GetBuffer() 方法从输出流中检索数据。请看这个blog entry获取更多信息。

public void SendEmailWithGZippedAttachment(string fromAddress, string toAddress, string subject, string body, string attachmentText)
{
const string filename = "myfile.csv.gz";
var message = new MailMessage(fromAddress, toAddress, subject, body);

//Compress and save buffer
var output = new MemoryStream();
using (var gzipStream = new GZipStream(output, CompressionMode.Compress))
{
using(var input = new MemoryStream(Encoding.UTF8.GetBytes(attachmentText)))
{
input.CopyTo(gzipStream);
}
}
//output.ToArray is still accessible even though output is closed
byte[] buffer = output.ToArray();

//Attach and send email
using(var stream = new MemoryStream(buffer))
{
message.Attachments.Add(new Attachment(stream, filename, "application/x-gzip"));
var smtp = new SmtpClient("mail.myemailserver.com") {Credentials = new NetworkCredential("username", "password")};
smtp.Send(message);
}
}

关于c# - 使用 GZIP 流和内存流正确压缩 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4998094/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com