嗨,我在我的WPF应用程序中有一个按钮,它从压缩文件中提取一组文件。我需要在提取文件夹中的文件工作。但提取后,如果我访问该文件,我不断得到一个异常,说明"文件已被其他进程使用,无法访问"。我使用了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:UnzippedSomething.xml");
// Something.xml has been used by some other process
提取工作正常。但提取后,当我访问文件在C:Unzippedsomething.xml我一直得到这个错误。"进程无法访问文件'C:UnzippedSomething.xml',因为它正在被另一个进程使用。"我怎么解决它?
您应该通过使用语句包装它们来处理可丢弃的资源:
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);
}
}
}