其实我试图创建一个目录的zip文件,但ZipFile.CreateFromDirectory()
给出了以下异常。
System.IO.IOException:进程无法访问该文件 PATH_TO_CREATE_ZIP / file.zip'因为它被另一个人使用 过程
以下是它的代码片段。 :
public void createZipFile(string zipPath, string archiveFileName)
{
string DirectoryToBeArchive = zipPath + "\\" + archiveFileName;
if (Directory.Exists(DirectoryToBeArchive + ".zip"))
{
File.Delete(DirectoryToBeArchive);
ZipFile.CreateFromDirectory(zipPath, DirectoryToBeArchive + ".zip", CompressionLevel.Fastest, false);
}
else
ZipFile.CreateFromDirectory(zipPath, DirectoryToBeArchive + ".zip", CompressionLevel.Fastest, false);
Directory.Delete(DirectoryToBeArchive);
}
帮助会得到很多赞赏。提前致谢。 :)
答案 0 :(得分:2)
只有你才能得到这个例外。让我们一步一步地调查您的代码:
createZipFile("C:\\Temp", "myZipFile");
public void createZipFile(string zipPath, string archiveFileName)
{
//DirectoryToBeArchive = "C:\\Temp\\myZipFile"
string DirectoryToBeArchive = zipPath + "\\" + archiveFileName;
//Some logical error here, you probably meant to use File.Exists()
//Basically, as you can't find a directory with name C:\\Temp\\myZipFile.zip, you always jump into else
if (Directory.Exists(DirectoryToBeArchive + ".zip"))
{
File.Delete(DirectoryToBeArchive);
ZipFile.CreateFromDirectory(zipPath, DirectoryToBeArchive + ".zip", CompressionLevel.Fastest, false);
}
else
//It will try to overwrite your existing "DirectoryToBeArchive".zip file
ZipFile.CreateFromDirectory(zipPath, DirectoryToBeArchive + ".zip", CompressionLevel.Fastest, false);
//This won't work as well btw, as there probably is no directory
//with name C:\\Temp\\myZipFile
Directory.Delete(DirectoryToBeArchive);
}
尽管如此,即使您删除了该文件,您也可能会遇到同样的错误。
问题是,当您尝试将文件夹C:\\Temp
压缩到文件C:\\Temp\\myZipFile.zip
中时,您也会尝试压缩文件本身。这实际上是你得到文件正在使用的错误。
所以,
使用File.Exists()
在另一个文件夹中压缩
只是一个友好的警告,如果我是你,我会对Directory.Delete()保持谨慎:)
答案 1 :(得分:0)
正确代码:
这段代码经过一些小修改后对我有用..
string DirectoryToBeArchive = zipPath + "\\" + archiveFileName;
if (File.Exists(DirectoryToBeArchive + ".zip"))
{
File.Delete(DirectoryToBeArchive + ".zip");
ZipFile.CreateFromDirectory(DirectoryToBeArchive, DirectoryToBeArchive + ".zip", CompressionLevel.Fastest, false);
}
else
ZipFile.CreateFromDirectory(DirectoryToBeArchive, DirectoryToBeArchive + ".zip", CompressionLevel.Fastest, false);
Directory.Delete(DirectoryToBeArchive , true);