可以创建 zip 密码保护文件,而无需先创建文件,然后将其压缩

Is possible to create zip password protected file without first creating file, then zip it

我正在将数据写入文本文件并使用以下代码,

 await using var file = new StreamWriter(filePath);
        foreach (var packet in resultPackets)
        {
            file.WriteLine(JsonConvert.SerializeObject(packet));
        }

我正在使用以下代码压缩文件,并使用`DotNetZip 保护密码,

 using (ZipFile zip = new ZipFile())
        {
            zip.Password = "password";
            zip.AddFile(filePath);
            zip.Save(@"C:\tmp\data4.zip");
        }

有没有办法将两者结合起来,我想即时创建一个受密码保护的文件。

我没有

这可能吗?谢谢!

好的,既然这个问题仍然没有得到解答,这里有一个小程序可以帮我完成这项工作:

using (var stream = new MemoryStream())
using (var streamWriter = new StreamWriter(stream))
{
    // Insert your code in here, i.e.
    //foreach (var packet in resultPackets)
    //{
    //   streamWriter.WriteLine(JsonConvert.SerializeObject(packet));
    //}

    // ... instead I write a simple string.
    streamWriter.Write("Hello World!");

    // Make sure the contents from the StreamWriter are actually flushed into the stream, then seek the beginning of the stream.
    streamWriter.Flush();
    stream.Seek(0, SeekOrigin.Begin);

    using (ZipFile zip = new ZipFile())
    {
        zip.Password = "password";

        // Write the contents of the stream into a file that is called "test.txt"
        zip.AddEntry("test.txt", stream);

        // Save the archive.
        zip.Save("test.zip");
    }
}

请注意 AddEntry 如何不创建任何形式的临时文件。相反,当存档被保存时,流的内容被读取并放入存档内的压缩文件中。但是,请注意,在将存档写入磁盘之前,文件的全部内容已完全保存在内存中。