C#中是否允许重用流?

问题描述 投票:1回答:1

这是我的代码。

using (FileStream zipToOpen = new FileStream(@"D:\test\1.txt", FileMode.Open))
            {
                using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
                {
                    ZipArchiveEntry readmeEntry = archive.CreateEntry("Readme.txt");
                    using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
                    {
                        writer.WriteLine("Information about this package.");
                        writer.WriteLine("========================");
                    }
                }

                // I reused this stream again and below code just a sample.
                // It would get exception
                using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
                {
                    //System.ArgumentException: 'Update mode requires a stream with read, write, and seek capabilities.'
                }
            }

是不是由'stream无法在C#中重新引发此异常?如果答案是肯定的,那么任何办公文件都可以让我参考吗?

谢谢,如果您能提供一些帮助,我们将不胜感激。

c# stream
1个回答
1
投票
默认情况下,ZipArchive承担对其所处理的Stream的生命周期控制,并在处理

it时进行处理。为避免这种情况,请在构造函数重载中将leaveOpen设置为true。但是:在用法之间您可能还需要rewind流,因此在两个zipToOpen.Position = 0;块之间需要using。有趣的是,似乎[[不太可能 1.txt是一个zip文件,但是...我想可能是!]]

© www.soinside.com 2019 - 2024. All rights reserved.