c# ZipFile.CreateFromDirectory - the process cannot access the file "path_to_the_zip_file_created.zip" because it is being used by another process

//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.


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);
            }
        }
    }
}