Basic Code:
string startPath = @\"C:\\intel\\logs\";
string zipPath = @\"C:\\intel\\logs-\" + DateTime.Now.ToString(\"
I came across this while because I was trying to zip the folder where my log files were being actively written by a running application. Kyle Johnson's answer could work, but it adds the overhead of copying the folder and the necessity of cleaning up the copy afterwards. Here's some code that will create the zip even if log files are being written to:
void SafelyCreateZipFromDirectory(string sourceDirectoryName, string zipFilePath)
{
using (FileStream zipToOpen = new FileStream(zipFilePath, FileMode.Create))
using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
{
foreach (var file in Directory.GetFiles(sourceDirectoryName))
{
var entryName = Path.GetFileName(file);
var entry = archive.CreateEntry(entryName);
entry.LastWriteTime = File.GetLastWriteTime(file);
using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var stream = entry.Open())
{
fs.CopyTo(stream, 81920);
}
}
}
}
The other answers, provide the correct reason, but I had a little problem in understanding them at the first sight. I cannot comment, so putting this as an Answer. Might be easy for someone who visits this later on.
If the path of the Zip file that is being created, is the same as the path that is given to the ZipFile.CreateFromDirectory, the ZipFile creates the desired zip file and starts adding the files from the directory to it. And will Eventually, try to add the desired zip file in the zip as well, as it is in the same directory. This is just not possible and not required, because the desired zipfile is being used by CreateFromDirectory method.
I had the exact same problem. The workaround is to copy the folder you are zipping to another folder and point CreateFromDirectory there. Don't ask me why this works but it does.
Directory.CreateDirectory(<new directory path>);
File.Copy(<copy contents into new folder>);
ZipFile.CreateFromDirectory(<new folder path>, <zipPath>);
//WRONG
ZipFile.CreateFromDirectory("C:\somefolder", "C:\somefolder\somefile.zip");
//RIGHT
ZipFile.CreateFromDirectory("C:\somefolder", "C:\someotherfolder\somefile.zip");
I use to do the same error: zipping a file into the same folder that I'm zipping.
This causes an error, of course.
If you're getting this error because NLog is locking your log files, you can use the following workaround. Add 'keepFileOpen' attribute to your nlog tag inside NLog.config and set it to false:
<nlog xmlns=.......
keepFileOpen="false"
....>
More details here.
Note that this setting will have negative performance on NLog logging as indicated here.