How to access Sqlite database file in Xamarin UWP

萝らか妹 提交于 2019-12-12 02:25:35

问题


I have a Xamarin project. In my UWP project's root, I stored a sqlite file that has initial tables my app needs. I set the 'Build Action' to 'Content'. All examples I found look for the file in 'ApplicationData.Current.LocalFolder.Path', but when I run the app, there is nothing in that folder. Everything gets created in Debug folder. Should I use a different path for debug and release? How does the storage work? Are apps being sandboxed in UWP?


回答1:


All examples I found look for the file in 'ApplicationData.Current.LocalFolder.Path', but when I run the app, there is nothing in that folder

Yes, the sqlite file you have set is just a Content for the UWP app, we need to copy it to LocalFolder programmatically in the first run. Using StorageFile.CopyAsync() method to copy file to the specific location

Please see Sunteen's answer in this question

Another location is Application data locations which can read/write. You can copy the database file from install directory to the application data directory for using. The following code example is for connecting a database file that in the local folder......




回答2:


In general how I completed my one is,

  • Make sure you installed this

  • For Windows apps (UWP, WP8,WP8.1 etc) all content files should be stored at root level (no sub folder. Maybe there is a workaround for this but It is default). For me this is very messy to store like that. Therefore I created a shared project to store sqllite.db and images etc. any shared files for all windows applications. set Build Action= content and Copy to Output Directory= Do not Copy

  • async way

    var sqliteFilename = "myworkout.db3";
    
    string     path=Path.Combine(ApplicationData.Current.LocalFolder.Path,sqliteFilename);
    
    var platform = new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT();
                    var task = Task.Run(async () => { await CopyDatabase(); });
                    task.Wait();
    

    var _sqliteConnectionWithLock = new SQLite.Net.SQLiteConnectionWithLock(platform,new SQLite.Net.SQLiteConnectionString( path, false));

    var conn = new SQLiteAsyncConnection(() => _sqliteConnectionWithLock);

  • sync code

    var sqliteFilename = "mydatabase.db3";

              string path = Path.Combine(ApplicationData.Current.LocalFolder.Path,
      sqliteFilename);
    
              var platform = new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT();
    
                  var task = Task.Run(async () => { await CopyDatabase(); });
              task.Wait();
    
               var conn = new SQLiteConnection(platform,path);
    


来源:https://stackoverflow.com/questions/38512257/how-to-access-sqlite-database-file-in-xamarin-uwp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!