拒绝访问删除正在读取的 zip 存档的 zip 文件

huangapple go评论84阅读模式
英文:

Access denied deleting zip file with zip archive being read

问题

以下是您要翻译的内容:

免责声明:这个问题不涉及Dispose()方法的应用。也不涉及文件不可访问的问题。我要做的是以正确的方式关闭存档,而不是依赖于对象的释放。

以下方法有效。

ZipFile.ExtractToDirectory(file, path, true);
File.Delete(file);

这个方法会因为文件被另一个进程使用而失败,抛出异常:由于另一个进程正在使用文件 'c:\temp...\file.zip',所以无法访问该文件

ZipFile.ExtractToDirectory(file, path, true);
ZipArchive archive = ZipFile.OpenRead(file);
File.Delete(file);

我通过释放对象来解决了这个问题。

ZipFile.ExtractToDirectory(file, path, true);
ZipArchive archive = ZipFile.OpenRead(file);
archive.Dispose();
File.Delete(file);

我担心释放对象不是正确的方法。不知何故,我觉得应该有一种在删除文件之前关闭文件的方法。但是,没有这样的方法。我进行了谷歌搜索,但得到的结果与内存流、一般访问被拒绝手动设置属性有关。

英文:

disclaimer This question isn't about the appliction of Dispose(). It's not about files being inaccessible. I'm about closing the archive in the proper way without relying on disposing the object.

The following works.

ZipFile.ExtractToDirectory(file, path, true);
File.Delete(file);

This fails with exception: The process cannot access the file 'c:\temp...\file.zip' because it is being used by another process.

ZipFile.ExtractToDirectory(file, path, true);
ZipArchive archive = ZipFile.OpenRead(file);
File.Delete(file);

I've resolved it by disposing the object.

ZipFile.ExtractToDirectory(file, path, true);
ZipArchive archive = ZipFile.OpenRead(file);
archive.Dispose();
File.Delete(file);

I am worried that disposing the object is not the correct approach. Somehow I feel there should be a way to close the file before deletion. There is no such method, however. I googled it but the results I got were about memory streams, general access being denied, manual setting of the attributes.

答案1

得分: 1

ZipFileZipArchive 实现了 IDisposable 接口,这意味着它会在作用域结束时自动调用 Dispose() 方法。请尝试使用以下代码块:

void SomeMethod(string file)
{
  using ZipArchive archive = ZipFile.OpenRead(file);
  ...
}
英文:

The ZipFile and ZipArchive implement IDisposable, which means that it'll invoke a call to Dispose() automagically at the end of the scope. Try using block as below.

void SomeMethod(string file)
{
  using ZipArchive archive = ZipFile.OpenRead(file);
  ...
}

huangapple
  • 本文由 发表于 2023年5月24日 22:18:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76324546.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定