Generating zip from Log4Net log files throws System.IO.IOException

I am using a simple piece of code to generate a zip file from log4net log files. See code below.

var logFiles = Directory.GetFiles(log4netfolderName, "*.log*");
 using (var zip = ZipFile.Open(destinationDirectory.DirectoryPath  + "Test.zip", 
 ZipArchiveMode.Create))
 {
     foreach (var file in logFiles)
     {
         zip.CreateEntryFromFile(file, 
         Path.GetFileName(file), CompressionLevel.Optimal);
     } 
 }

      

The problem is that log4net is currently using the log file and I get " The process cannot access the file" because it is being used by another process. "(System.IO.IOException)

Also I cannot change the log4net configuration to use minimal blocking as stated in The process cannot access the "MyFile.log" file because it is being used by another process or does not know how to use the FileStream for the ZipFile class. How to fix it?

+3


source to share


1 answer


Found the ZipFileExtensions class and used its code to re-write mine. The fix goes like this, feel free to fix or improve my answer.



var logFiles = Directory.GetFiles(folderName,"*.log.*");
using (var zip = ZipFile.Open(destinationDirectory.DirectoryPath + "Test.zip",
ZipArchiveMode.Create))
{
    foreach (var file in logFiles)
    {
        using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read,
            FileShare.Delete | FileShare.ReadWrite))
        {
            var zipArchiveEntry = zip.CreateEntry(Path.GetFileName(file),
                CompressionLevel.Optimal);
            using (var destination1 = zipArchiveEntry.Open())
                stream.CopyTo(destination1);
        }
    }
}

      

+6


source







All Articles