0
votes

To avoid creating double SQLite DB, How to detect if there is one already ?

1) Below code is creating SQLite DB in App.xaml.cs

2) Is this code in App.xaml.cs creating a SQLite DB or creating just Table or BOTH?

3) in MainPage, How Do I check One more time if SQLite DB is created.

Problem: no erro message and MainPage is not showing.

Your help is appreciated. Thanks


 -- In below checking rootFrame in  App.xaml.cs

if (rootFrame == null)
{


 //-- Detect before creating 

 bool result = await GetIfFileExistsAsync(DBPath);


 if (result == true)               
 {
      MessageDialog mError = new MessageDialog("DB Created", "DB creation status");
     await mError.ShowAsync();
     return;

 }
 else
  {
    MessageDialog mError = new MessageDialog("DB NOT Created", "NO DB created");
   await mError.ShowAsync();

   CreateDBNow();

   }

//---- rootFrame

}




 private async Task GetIfFileExistsAsync(string strDBPath)
 {
    try
     {

     var dbFile = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(strDBPath);

      if (dbFile != null)
      {
       return true;
      }
     else
      {
        return false;
      }


    }
    catch (FileNotFoundException)
    {
      return false;

    }
 }

 private async void CreateDBNow()
 {

    DBPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "customers.sqlite");


   using (var db = new SQLite.SQLiteConnection(DBPath))
   {
    // Create the tables if they don't exist
    db.CreateTable();

   }

  MessageDialog mError = new MessageDialog("DB now created", "DB created");
  await mError.ShowAsync();


  }


--- in MainPage 
I need to check one more time if SQLite DB is created.
1

1 Answers

0
votes

As a best practice developers store database in local folder, so below given handy method will help you. WinRT doesn't have feature to check whether file exist or not. So this is applicable to check not only for database file but all StorageFile.

public async Task<bool> IsDatabaseExistsAsync(string DatabaseNameWithExtension)
{
    try
    {
        var dbFile = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(DatabaseNameWithExtension);
        return true;
    }
    catch (Exception)
    {
        return false;
    }
}