我在VS2012,WinRT和C#工作。
我正在尝试在解压缩后删除一些文件。我收到“访问被拒绝”错误。如果我停止应用程序并重新启动它,相同的代码工作正常,因此它似乎仍然附加了句柄。
如果我不调用unZipFile方法,我可以删除这些文件。
是否有明确的方式来发布文件?我在调用delete之前将它设置为null(file = null;)。
以下是调用解压缩方法的代码块:
StorageFile file = await CreateOutputFile(fileName, path);
MemoryStream theMemStream = new MemoryStream();
theMemStream.Write(bytes, 0, bytes.Length);
await FileIO.WriteBytesAsync(file, bytes);
await theMemStream.FlushAsync();
theMemStream.Dispose();
var result = await unZipFile(file, path);
file = null;
这是unZipFile方法:
private async Task<string> unZipFile(StorageFile file, string path)
{
StorageFolder sf = await GetOutputFolder(path);
using (var zipStream = await file.OpenStreamForReadAsync())
{
using (MemoryStream zipMemoryStream = new MemoryStream((int)zipStream.Length))
{
await zipStream.CopyToAsync(zipMemoryStream);
try
{
var archive = SharpCompress.Archive.ArchiveFactory.Open(file.Path);
foreach (var entry in archive.Entries)
{
entry.WriteTo(zipMemoryStream);
Stream fileData = entry.OpenEntryStream();
StorageFile outputFile = await sf.CreateFileAsync(entry.FilePath, CreationCollisionOption.ReplaceExisting);
using (Stream outputFileStream = await outputFile.OpenStreamForWriteAsync())
{
await fileData.CopyToAsync(outputFileStream);
await outputFileStream.FlushAsync();
outputFileStream.Dispose();
}
}
archive = null;
}
catch (Exception ex)
{
throw new IOException("Error writing decompressed output file: " + ex.Message);
}
await zipStream.FlushAsync();
zipStream.Dispose();
await zipMemoryStream.FlushAsync();
zipMemoryStream.Dispose();
}
}
return "success";
}
这是删除方法。解压后为每个文件调用:
private async Task<string> deleteFile(string path, string filename)
{
StorageFolder folder = await GetOutputFolder(path);
var files = await folder.GetFilesAsync();
foreach (StorageFile file in files)
{
try
{
if (file != null)
{
if (file.Name == filename)
await file.DeleteAsync();
}
}
catch (Exception ex)
{
return ex.Message;
}
}
return "success";
}
答案 0 :(得分:3)
您在哪个文件中获取异常,提取的文件或zip存档本身?
如果是后一种情况,ArchiveFactory.Open()
会返回继承IArchive
的{{1}},因此您应该将IDisposable
包裹在var archive = SharpCompress.Archive.ArchiveFactory.Open(file.Path);
块中,以便它获得使用后处理。