UWP - Sqlitepcl database in mobile emulator. Fetching database path on SD card

时间:2016-12-09 12:59:17

标签: c# sql sqlite xaml uwp

I've already created the database and I'm trying to make the sqliteconnection and link it to the filepath of the database, which i've placed on the simulated sdcard.

This is my code for the database connection:

public static class DatabaseManager
{

    public static SQLiteConnection dbConnection = new SQLiteConnection("MusicAppM.db");

    public static async void CreateMobileDB()
    {

        StorageFile db = null;
        StorageFolder folder = KnownFolders.RemovableDevices;
        await RetrieveDbInFolders(db, folder);
        string ConnString = Path.Combine(db.Path, "MusicAppM.db");
        SQLiteConnection dbConnection = new SQLiteConnection(ConnString);

    }

    private static async Task RetrieveDbInFolders(StorageFile db, StorageFolder parent)
    {
        foreach (var item in await parent.GetFilesAsync())
        {
            if (item.FileType == ".db")
                db = item;
        }
        foreach (var item in await parent.GetFoldersAsync())
        {
            await RetrieveDbInFolders(db, item);
        }
    }
}

However, my function "retrievedbinfolders" never returns the database file even though I've placed it in the folder which is the simulated sdcard. Why is this?

On a second note I'm not sure if the path.combine will link the database connection to the filepath, so I'm contemplating wether or not I'm better of just setting up a server instead.

1 个答案:

答案 0 :(得分:1)

1.为什么函数“retrievebinfolders”永远不会返回数据库文件?

当对象实例作为参数传递给方法时,参数的值是对对象的引用。可以在被调用的方法中更改对象的内容,但永远不会更改对象引用

代码:

public static class DatabaseManager
{
    public static SQLiteConnection dbConnection = new SQLiteConnection(new SQLitePlatformWinRT(), "MusicAppM.db");
    // private static StorageFile db = null;

    public static async void CreateMobileDB()
    {
        StorageFile db = null;
        // StorageFolder folder = KnownFolders.RemovableDevices;
        StorageFolder folder = ApplicationData.Current.LocalFolder;
        await RetrieveDbInFolders(db, folder, (parm) =>
            { db = parm; });
        if (db != null)
        {
            SQLiteConnection dbConnection = new SQLiteConnection(new SQLitePlatformWinRT(), db.Path);
        }
        else
        {
            string ConnString = Path.Combine(folder.Path, "MusicAppM.db");
            SQLiteConnection dbConnection = new SQLiteConnection(new SQLitePlatformWinRT(), ConnString);
        }
    }

    private static async Task RetrieveDbInFolders(StorageFile db, StorageFolder parent, Action<StorageFile> callback = null)
    {
        foreach (var item in await parent.GetFilesAsync())
        {
            if (item.FileType == ".db")
                db = item;
            callback(db);
        }
        foreach (var item in await parent.GetFoldersAsync())
        {
            await RetrieveDbInFolders(db, item);
        }
    }
}

这可能是你想要的