gpt4 book ai didi

c# - 无法使用 DeleteAsync 删除文件

转载 作者:行者123 更新时间:2023-11-30 22:23:34 25 4
gpt4 key购买 nike

我在 VS2012、WinRT 和 C# 中工作。

我试图在解压后删除一些文件。我收到“访问被拒绝”错误。如果我停止该应用程序并重新启动它,相同的代码可以正常工作,所以看起来仍然有一个 handle 。

如果我不调用 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";
}

最佳答案

在什么文件上出现异常,是提取的文件还是 zip 存档本身?

如果是后者,ArchiveFactory.Open() 返回一个继承IDisposableIArchive,所以你应该包装 var archive = SharpCompress.Archive.ArchiveFactory.Open(file.Path);using block 中,以便在使用后处理。

关于c# - 无法使用 DeleteAsync 删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13310933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com