Pergunta

I have no idea why this won't work - starting to drive me crazy!

Nobody else seems to have this problem

My code looks something like this:

        Stream stream = new MemoryStream();
        try
        {
            // output zip
            using (ZipFile zipFile = new ZipFile())
            {
                zipFile.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
                ForEach(DataFile file In DataFiles)
                {
                    String sourcePath = dataFile.Path;
                    String archiveName = dataFile.RealName;
                    //byte[] fileContents = File.ReadAllBytes(sourcePath);
                    //zipFile.AddEntry(archiveName, fileContents);
                    zipFile.AddFile(sourcePath, archiveName);
                    //e.FileName = archiveName;
                }

                zipFile.AddEntry("README.TXT", readmeMessage);
                zipFile.Save(stream);
            }
        }
        catch (Exception ex)
        {
            throw;
        }

All the file paths are valid.

Adding the readme file works fine, if I comment out the rest. But adding the other files causes the zip file to be invalid.

I would appreciate any suggestions!

Thanks

UPDATE

I've noticed that if I initialise the stream with exactly the right size it works. Does anyone know how to get the size of the archive without writing it to disk?

FURTHER UPDATE

I've added a workaround for now.

I can do what I need to by saving the archive to disk then reading it back into another stream

Very lame and I really don't like it, so if anyone can suggest a better way I'd be grateful!

Foi útil?

Solução 2

It seems that once the zip archive reaches a certain size (I haven't tested enough to be sure of the actual limit) it cannot be reliably saved to a stream.

Although nobody seems to be saying it, the only way around this is to save the archive to disk.

Outras dicas

I've never worked with it, but looking into the examples (some checking, comments and no relevant lines removed) of the DotNetZip Library I found this:

public static void Main(String[] args)
{
    ... some input checking ...

    string ZipFileToCreate = args[0];
    string DirectoryToZip = args[1];
    try
    {
        using (ZipFile zip = new ZipFile())
        {
            // note: this does not recurse directories! 
            String[] filenames = System.IO.Directory.GetFiles(DirectoryToZip);
            foreach (String filename in filenames)
            {
                Console.WriteLine("Adding {0}...", filename);
                ZipEntry e = zip.AddFile(filename);
                e.Comment = "Added by Cheeso's CreateZip utility.";
            }

            zip.Save(ZipFileToCreate);
        }
    }
    catch (System.Exception ex1)
    {
        System.Console.Error.WriteLine("exception: " + ex1);
    }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top