簡體   English   中英

使用GZipStream將文本文件寫入gz文件,而無需先將文本文件寫入磁盤

[英]Writing a text file into a gz file using GZipStream without first writing the text file to disk

我目前正在通過一些數據庫查詢生成大量輸出。 生成的XML文件約為2GB。 (這是一年的數據)。 為了節省客戶端的磁盤空間和下載時間,我正在使用GZipStream類將此文件添加到壓縮文件中。 請參閱下文,了解我當前如何將文件壓縮為gz。 注意:fi對象是FileInfo。

using (FileStream inFile = fi.OpenRead())
using (FileStream outFile = File.Create(fi.FullName + ".gz"))
using (GZipStream Compress = new GZipStream(outFile, CompressionMode.Compress))
{
    byte[] buffer = new byte[65536];
    int numRead;
    while ((numRead = inFile.Read(buffer, 0, buffer.Length)) != 0)
    {
        Compress.Write(buffer, 0, numRead);
    }
}

此方法工作正常,但需要我將2GB文本文件寫出到磁盤,然后再次全部讀回以將其添加到GZipStream,然后再將其作為壓縮文件寫回。 似乎浪費時間。

有沒有一種方法可以將我的2GB字符串直接添加到GZipStream,而無需首先寫入磁盤?

您可以從GZipStream創建StreamWriter (或者在您的情況下可能是XmlWriter ),而只需寫入它即可。

using (FileStream outFile = File.Create(fi.FullName + ".gz"))
using (GZipStream compress = new GZipStream(outFile, CompressionMode.Compress))
using (StreamWriter writer = new StreamWriter(compress))
{
    foreach(string line in GetLines())
        writer.WriteLine(line);
}

如果有任何方法可以將數據庫結果轉換為字符串,然后將其加載到MemoryStream中,那么應該沒問題:

        var databaseResult = "<xml>Very Long Xml String</xml>";

        using (var stream = new MemoryStream())
        {
            using (var writer = new StreamWriter(stream))
            {
                writer.Write(databaseResult);
                writer.Flush();
                stream.Position = 0;

                using (var outFile = File.Create(@"c:\temp\output.xml.gz"))
                using (var Compress = new System.IO.Compression.GZipStream(outFile, CompressionMode.Compress))
                {
                    var buffer = new byte[65536];
                    int numRead;
                    while ((numRead = stream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        Compress.Write(buffer, 0, numRead);
                    }
                }
            }
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM