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

前端 未结 5 1376
礼貌的吻别
礼貌的吻别 2020-12-03 04:22

Basic Code:

string startPath = @\"C:\\intel\\logs\";
string zipPath = @\"C:\\intel\\logs-\" + DateTime.Now.ToString(\"         


        
5条回答
  •  借酒劲吻你
    2020-12-03 04:52

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

提交回复
热议问题