[英]Why am I getting a file creation error Windows 8 Store app
运行程序时出现文件创建错误,但是如果使用调试器逐步执行该程序,则会在data文件夹中复制并创建文件。 下面是错误消息。
//当该文件已存在时无法创建该文件。 (来自HRESULT的异常:0x800700B7)
这是代码。
private string dbName1 = "ExpressEMR.db";
public MainPage()
{
this.InitializeComponent();
LoadDataTask();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
private async void LoadDataTask()
{
await CreateIfNotExists(dbName1);
}
private async Task CreateIfNotExists(string dbName1)
{
if (await GetIfFileExistsAsync(dbName1) == null)
{
StorageFile seedFile = await StorageFile.GetFileFromPathAsync(Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, dbName1));
await seedFile.CopyAsync(Windows.Storage.ApplicationData.Current.LocalFolder);
}
}
private async Task<StorageFile> GetIfFileExistsAsync(string key)
{
try
{
return await ApplicationData.Current.LocalFolder.GetFileAsync(key);
}
catch (FileNotFoundException)
{
return default(StorageFile);
}
}
您应该考虑将具有异常功能的代码移出构造函数。 考虑改为提供this.Loaded事件,以便构造函数在应用加载状态之前首先完成。
public MainPage()
{ {
this.InitializeComponent();
this.Loaded += async (se, ev) =>
{
LoadDataTask();
};
}
此外,LoadDataTask应该返回一个Task而不是Void。
private async TaskLoadDataTask()
{
await CreateIfNotExists(dbName1);
}
private async Task CreateIfNotExists(string dbName1)
{
var fileExists = await GetIfFileExistsAsync(dbName1) != null;
if (!fileExists)
{
var filePath = Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, dbName1);
var seedFile = await StorageFile.GetFileFromPathAsync(filePath);
await seedFile.CopyAsync(Windows.Storage.ApplicationData.Current.LocalFolder);
}
}
最后,您似乎在两个不同的位置进行搜索:
Windows.ApplicationModel.Package.Current.InstalledLocation.Path
和
ApplicationData.Current.LocalFolder
这些路径真的一样吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.