Why am I getting a file creation error Windows 8 Store app

0

I get a file creation error when I run the program, but if I step through the program with the debugger, the file gets copied and created in the data folder. Below is the error msg.

//Cannot create a file when that file already exists. (Exception from HRESULT: 0x800700B7)

Here is the code.

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);
            }
        }
c#
visual-studio-2012
windows-store-apps
asked on Stack Overflow Jul 23, 2014 by Trey Balut

1 Answer

0

You should consider moving exception capable code out of your constructor. Consider providing a this.Loaded event instead so that your constructor completes first before the app loads state.

public MainPage()
{    {
   this.InitializeComponent();

   this.Loaded += async (se, ev) =>
   {
      LoadDataTask();
   };
}  

In addition, LoadDataTask should return a Task and not 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);
    }
}

Lastly, it looks like you are searching in two different locations:

Windows.ApplicationModel.Package.Current.InstalledLocation.Path

and

ApplicationData.Current.LocalFolder

Are these really the same paths?

answered on Stack Overflow Aug 6, 2014 by Scott Nimrod

User contributions licensed under CC BY-SA 3.0