0

我正在处理的程序目前正在使用 aStreamWriter在目标文件夹中创建一个或多个文本文件。关闭StreamWriter类,我通过指令使用WriteLine它的IDisposable接口Using(对于隐式.Close)。

我需要添加一个选项以在目标文件夹内的 zip 存档中创建一个或多个文本文件。我打算更改现有代码以使用流,因此可以使用 ZIP 文件作为输出(计划使用DotNetZip)。

我正在考虑创建一些GetOutputStream功能并将其提供给当前存在的方法。此函数将确定是否设置了归档选项,并创建普通文件或归档它们。问题是MemoryStream看起来像一个很好的缓冲区类与 一起使用,在继承层次结构DotNetZip中不相交。StreamWriter

看起来我唯一的选择是创建一些IWriteLine接口,它将实现WriteLineIDisposable. StreamWriter然后从和分支两个新的子类MemoryStream,并IWriteLine在其中实现。

有更好的解决方案吗?

当前代码在概念上如下所示:

Using sw As StreamWriter = File.CreateText(fullPath)
  sw.WriteLine(header)
  sw.WriteLine(signature)
  While dr.Read 'dr=DataReader
    Dim record As String = GetDataRecord(dr)
    sw.WriteLine(record)
  End While
End Using

对于代码示例,VB.NETC#都可以,尽管这更像是一个概念性问题。

编辑:不能使用 .NET 4.5 System.IO.Compression.ZipArchive,必须坚持使用 .NET 4.0。我们仍然需要支持在 Windows 2003 上运行的客户端。

4

2 回答 2

1

首先,使用 .NET 4.5 System.IO.Compression.ZipArchive 类(请参阅http://msdn.microsoft.com/en-us/library/system.io.compression.ziparchive.aspx),您不再需要 DotNetZip至少对于常见的压缩任务。

它可能看起来像这样:

        string filePath = "...";

        //Create file.
        using (FileStream fileStream = File.Create(filePath))
        {
            //Create archive infrastructure.
            using (ZipArchive archive = new ZipArchive(fileStream, ZipArchiveMode.Create, true, Encoding.UTF8))
            {
                SqlDataReader sqlReader = null;

                //Reading each row into a separate text file in the archive.
                while(sqlReader.Read())
                {
                    string record = sqlReader.GetString(0);

                    //Archive entry is a file inside archive.
                    ZipArchiveEntry entry = archive.CreateEntry("...", CompressionLevel.Optimal);

                    //Get stream to write the archive item body.
                    using (Stream entryStream = entry.Open())
                    {
                        //All you need here is to write data into archive item stream.
                        byte[] recordData = Encoding.Unicode.GetBytes(record);
                        MemoryStream recordStream = new MemoryStream(recordData);
                        recordStream.CopyTo(entryStream);

                        //Flush the archive item to avoid data loss on dispose.
                        entryStream.Flush();
                    }
                }
            }
        }
于 2013-07-29T19:40:38.107 回答
1

使用 StreamWriter(Stream) 构造函数将其写入 MemoryStream。将 Position 设置回 0,这样您就可以使用 ZipFile.Save(Stream) 将写入的文本保存到存档中。检查项目示例代码中的 ZipIntoMemory 辅助方法以获取指导。

于 2013-07-29T19:52:45.517 回答