Search code examples
c#asp.netfilestreamzipdotnetzip

Cannot access a closed file in ASP.Net (saving files in zip file)


I got this error "Cannot access a closed file" when I save more than one file in zip. This is the code. Error at zip.Save(NewZipPath);

internal static string UpdateZipFile(string PdfPath, string ZipPath, 
                    string NewZipPath, string docPath)
{
    try
    {
    using (ZipFile zip = ZipFile.Read(ZipPath))
    {
        FileStream fs = new FileStream(PdfPath, FileMode.Open, FileAccess.Read);

        DirectoryInfo Dir = new DirectoryInfo(docPath);

        FileInfo[] FileList = Dir.GetFiles("*.*", SearchOption.AllDirectories);

        foreach (FileInfo FI in FileList)
        {
        zip.AddEntry(FI.FullName, fs);
        }

        // Error at this line if more than one
        // files in above directory.
        zip.Save(NewZipPath);

        fs.Close();
        fs.Dispose();

        return "- ZIP Generated Successfully !";
    }
    }
    catch (Exception ex)
    {
    return ex.Message;
    }
}

Full exception

System.ObjectDisposedException: Cannot access a closed file.
   at System.IO.__Error.FileNotOpen()
   at System.IO.FileStream.get_Length()
   at Ionic.Zip.ZipEntry.SetInputAndFigureFileLength(Stream& input)
   at Ionic.Zip.ZipEntry._WriteEntryData(Stream s)
   at Ionic.Zip.ZipEntry._EmitOne(Stream outstream)
   at Ionic.Zip.ZipEntry.Write(Stream s)
   at Ionic.Zip.ZipFile.Save()
   at Ionic.Zip.ZipFile.Save(String fileName)
   at RideShare.Utility.UpdateZipFile(String PdfPath, 
String ZipPath, String NewZipPath, String docPath) in 

Thanks.


Solution

  • I think what's going on here is that the use of the stream "FS" is tangled up. You can spend time trying to untangle it, or you can use the simpler "AddFiles" method:

    Search for "Create a zip containing all the files in a folder." at

    http://dotnetzip.codeplex.com/wikipage?title=CS-Examples&referringTitle=Examples