开发者

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

开发者 https://www.devze.com 2023-03-29 18:13 出处:网络
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);

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 FileLi开发者_Python百科st)
        {
        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.


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


the exception happens because AddEntry uses the FileStram and after it is finished with the FileStream it closes it automatically.. so it is closed during Save after the first file... when there is one file it is ok - but your code adds the same FileStream fs for every file... not sure that this is what you really want... I think you would want to open one separate stream per file you add via AddEntry...

change your code to:

foreach (FileInfo FI in FileList)
    {
    zip.AddFile(FI.FullName);
    }

OR replace the foreach loop by

zip.AddFiles((from FI in Dir.GetFiles("*.*", SearchOption.AllDirectories) select FI.FullName).ToArray());
0

精彩评论

暂无评论...
验证码 换一张
取 消