C# 为什么Windows 8应用商店应用程序出现文件创建错误
当我运行程序时,我得到一个文件创建错误,但是如果我使用调试器单步执行程序,文件会被复制并在数据文件夹中创建。下面是错误消息 //当文件已存在时,无法创建该文件。来自HRESULT的异常:0x800700B7 这是代码C# 为什么Windows 8应用商店应用程序出现文件创建错误,c#,visual-studio-2012,windows-store-apps,C#,Visual Studio 2012,Windows Store Apps,当我运行程序时,我得到一个文件创建错误,但是如果我使用调试器单步执行程序,文件会被复制并在数据文件夹中创建。下面是错误消息 //当文件已存在时,无法创建该文件。来自HRESULT的异常:0x800700B7 这是代码 private string dbName1 = "ExpressEMR.db"; public MainPage() { this.InitializeComponent(); LoadDataTa
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);
}
}
您应该考虑从构造函数中移出异常能力代码。 考虑提供一个.Load事件,这样在应用程序加载状态之前,你的构造函数就先完成了。
public MainPage()
{ {
this.InitializeComponent();
this.Loaded += async (se, ev) =>
{
LoadDataTask();
};
}
此外,LoadDataTask应该返回一个任务,而不是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