[英]Cant delete a file in Windows Store Application - Access is denied. (HRESULT: 0x80070005 (E_ACCESSDENIED))
I'm writing a Windows Store Application. 我正在编写Windows应用商店应用程序。 I have to recreate a database in some cases (tests, new user, etc) - Sqlite is being used. 在某些情况下(测试,新用户等),我必须重新创建数据库-正在使用Sqlite。 I need to copy existing database to backup, delete existing database and then create a new database file with schema. 我需要将现有数据库复制到备份中,删除现有数据库,然后使用架构创建一个新的数据库文件。
The code: 编码:
public async Task<bool> CreateDatabaseAsync()
{
if (await PathUtils.FileExistsAsync(DbConstants.DbFileWithPath))
{
var currentDbFolder = await StorageFolder.GetFolderFromPathAsync(DbConstants.DbPath);
var currentdbFile = await StorageFile.GetFileFromPathAsync(DbConstants.DbFileWithPath);
await currentdbFile.CopyAsync(currentDbFolder, DbConstants.DbBackup, NameCollisionOption.ReplaceExisting);
//problem here with deletion
await currentdbFile.DeleteAsync(DbConstants.FilelDeletionOption);
}
return await CreateSchema();
}
private async Task<bool> CreateSchema()
{
var db = new SQLiteAsyncConnection(DbConstants.DbFileWithPath);
await db.CreateTablesAsync(typeof (Doc), typeof(DocAttachment));
db = null;
GC.Collect();
return true;
}
}
If I call method CreateDatabaseAsync() two times sequentially, db file will be created during the first call and UnauthorizedAccessException will be thrown during its deletion during the second call - see the comment. 如果我依次两次调用方法CreateDatabaseAsync(),则在第一次调用期间将创建db文件,而在第二次调用期间将其删除期间将抛出UnauthorizedAccessException-请参见注释。 I have no idea what can hold this file open. 我不知道什么可以使该文件保持打开状态。 See that I null the reference to SQliteAsyncConnetion and force a collection of all generations. 看到我对SQliteAsyncConnetion的引用为空,并强制收集所有世代。 Still, I cannot delete the file - {"Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"}. 不过,我仍无法删除文件-{“访问被拒绝。(HRESULT的异常:0x80070005(E_ACCESSDENIED))”}。
File is being created in ApplicationData.Current.LocalFolder.Path. 在ApplicationData.Current.LocalFolder.Path中创建文件。
Currently I'm trying to recreate the db during the each integration test. 目前,我正在尝试在每个集成测试期间重新创建数据库。
The problem is that SQLiteAsyncConnection
implements a connection pool - the pooling has the side effect of keeping the db file open. 问题是SQLiteAsyncConnection
实现了一个连接池-池的副作用是保持db文件打开。
The only solution I can see is to use the synchronous version of the API. 我看到的唯一解决方案是使用API的同步版本。 There is no pooling, and it allows you to close the db connection, and therefore close the file: 没有缓冲池,它允许您关闭数据库连接,并因此关闭文件:
private bool CreateSchema()
{
using (var db = new SQLiteConnection(DbConstants.DbFileWithPath))
{
db.CreateTables(typeof (Doc), typeof(DocAttachment));
}
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.