利用 GZIP 流和内存流正确压缩 CSV
我正在利用 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);
}
}
I am compressing a CSV file utilizing GZIPStream and MemoryStream, and noticing something weird with the result file. It seems like the CSV is not properly recognized. This shows when the file is attached to an email, but works fine when saved on a windows desktop.
Here is the current snippet handling the gzip portion:
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我能够使用下面的代码进行 gzip 压缩并发送 csv。 GZipStream 在调用其 Close() 方法之前不会完成写入。当创建 gzipStream 的 using 块完成时会发生这种情况。尽管在 using 块完成后流输出也会关闭,但仍然可以使用 ToArray() 或 GetBuffer() 方法从输出流中检索数据。有关详细信息,请参阅此博客条目。
I was able to gzip compress and send a csv using the code below. GZipStream doesn't complete writing until its Close() method is called. This happens when the using block that creates gzipStream is completed. Even though the stream output is also closed once that using block is completed, the data can still be retrieved from the output stream using the ToArray() or GetBuffer() methods. Please see this blog entry for more information.
所有建议的答案都不起作用。在这里找到了答案:
http://msdn.microsoft.com/en-us/magazine/cc163727.aspx
All the suggested answers did not work. Found the answer here:
http://msdn.microsoft.com/en-us/magazine/cc163727.aspx
GZipStream 不会创建 zip 存档;它只是实现了压缩算法。
请参阅此 MSDN 示例以创建 zip 文件: http://msdn.microsoft.com /en-us/library/ywf6dxhx.aspx
GZipStream does NOT create a zip archive; it simply implements the compression algorithm.
See this MSDN sample for creating a zip file: http://msdn.microsoft.com/en-us/library/ywf6dxhx.aspx