您好我的WPF应用程序中有一个按钮,它从zip中提取文件集。我需要处理解压缩文件夹中的文件。但是在提取之后,如果我访问该文件,我一直得到一个例外,说明"文件已被其他进程使用,无法访问"像那样。 我使用了Stream.flush(),Stream.Close(),Stream.Dispose()。它们都没有用。
var zipFilePath = @"C:\Output.zip";
var tempFolderPath = @"C:\Unzipped";
using (Package package = ZipPackage.Open(zipFilePath, FileMode.Open, FileAccess.Read))
{
foreach (PackagePart part in package.GetParts())
{
var target = Path.GetFullPath(Path.Combine(tempFolderPath, part.Uri.OriginalString.TrimStart('/')));
var targetDir = target.Remove(target.LastIndexOf('\\'));
if (!Directory.Exists(targetDir))
Directory.CreateDirectory(targetDir);
MemoryStream memoryStream = new MemoryStream();
using (Stream source = part.GetStream(FileMode.Open, FileAccess.Read))
// using (Stream source = new FileStream(, FileMode.Open))
{
source.CopyTo(File.OpenWrite(target));
// CopyStreamTo(source, memoryStream);
}
}
}
MessageBox.Show("Extracted in a folder");
myclass obj=new myclass(@"C:\Unzipped\Something.xml");
// Something.xml has been used by some other process
提取工作正常。但是当我在C:\ Unzipped \ something.xml中访问文件时提取后,我不断收到此错误。"进程无法访问文件' C:\ Unzipped \ Something.xml'因为它正被另一个进程使用。" 我怎么解决?
答案 0 :(得分:3)
您应该通过将IDisposable资源包含在using语句中来处置它们:
using (Package package = ZipPackage.Open(zipFilePath, FileMode.Open, FileAccess.Read))
{
foreach (PackagePart part in package.GetParts())
{
var target = Path.GetFullPath(Path.Combine(tempFolderPath, part.Uri.OriginalString.TrimStart('/')));
var targetDir = target.Remove(target.LastIndexOf('\\'));
if (!Directory.Exists(targetDir))
{
Directory.CreateDirectory(targetDir);
}
using (Stream source = part.GetStream(FileMode.Open, FileAccess.Read))
using (Stream targetFileStream = File.OpenWrite(target))
{
source.CopyTo(targetFileStream);
}
}
}