DotNetZip提取可防止进程访问文件

时间:2015-03-24 17:58:59

标签: c# .net file .net-4.0 dotnetzip

我使用DotNetZip库从zip文件中提取文件。

using(ZipFile zip = ZipFile.Read(zipLocation))
{
    foreach (ZipEntry entry in zip){
        entry.Extract(_updateDir);
        Log.Write("Unpacked: " + entry.FileName, Log.LogType.Info);
    }

    zip.Dispose();
}

稍后,我尝试编辑我提取的其中一个文件。

var updateList = allFiles.Where(x => x.Contains(".UPD"));
foreach (string upd in updateList){
    string[] result = File.ReadAllLines(upd);
    int index = Array.IndexOf(result, "[Info]");

    //then I do stuff with index
}    

string[] result = File.ReadAllLines(upd);

我得到例外:The process cannot access the file <file name> because it is being used by another process.

我知道抛出此异常是因为该文件正在其他地方使用。在File.ReadAllLines(upd)之前使用它的唯一地方是上面的DotNetZip代码。

DotNetZip代码中是否有办法防止这种情况发生?

1 个答案:

答案 0 :(得分:3)

问题不在于DotNetZip。我在我的项目中尝试了代码,它的工作原理是:

[Test]
        public void Test2()
        {
            using (ZipFile zip = ZipFile.Read("D:/ArchiveTest.zip"))
            {
                foreach (ZipEntry entry in zip)
                {
                    entry.Extract("D:/ArchiveTest");
                }

                zip.Dispose();
            }

            var updateList = Directory.GetFiles("D:/ArchiveTest").Where(x => x.Contains(".UPD"));
            foreach (string upd in updateList)
            {
                string[] result = File.ReadAllLines(upd);
                int index = Array.IndexOf(result, "[Info]");

                //then I do stuff with index
            }
        }

可能另一个进程正在使用您尝试阅读的文件。如果您使用的是Windows7或Windows8,则可以使用内置的资源监视器。阅读这篇文章:How to know what process is using a given file?