I am using a simple code snippet to create a zip file from the log4net log files. See the 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 the log4net is currently using the log file and I get a "The process cannot access the file '' because it is being used by another process." (System.IO.IOException)
Also I cannot change the log4net config to use a minimal lock as given in Process cannot access the file "MyFile.log" because it is being used by another process or dont know how to use FileStream on the ZipFile Class. How Should I fix this?
Found the ZipFileExtensions class and used its code to re-write mine. The fix goes like this, feel free to correct 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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With