【发布时间】:2018-07-11 12:19:55
【问题描述】:
我在解决方案的 Databases 文件夹中有一个名为 tryout2.db 的数据库。如果本地包文件夹上没有这样的数据库,那么我想将它从解决方案中的 Databases 文件夹复制到本地包文件夹。 代码:
public ViewModel()
{
ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
if (!localSettings.Values.ContainsKey("defaultCategories"))
{
CopyDatabase();
localSettings.Values["defaultCategories"] = true;
}
else
{
Categories();
}
}
private async void CopyDatabase()
{
StorageFile dbFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Databases/tryout2.db"));
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
await dbFile.CopyAsync(localFolder);
Categories();
}
public void Categories()
{
objConn = new SQLiteConnection("tryout2.db");
string strQ = @"SELECT * FROM DBQUIZ;";
var s = objConn.Prepare(strQ);
while (s.Step() == SQLiteResult.ROW)
{
Items.Add(new DBQUIZ(s[0].ToString(), s[1].ToString(), s[2].ToString(), s[3].ToString(),
s[4].ToString()));
}
}
更新:使用检查文件是否存在:
SQLitePCL.SQLiteConnection objConn;
public static string DB_PATH = Path.Combine(Path.Combine(ApplicationData.Current.LocalFolder.Path, "tryout2.db"));//DataBase Name
public ViewModel()
{
if (!CheckFileExists("tryout2.db").Result)
{
using (var db = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), DB_PATH))
{
CopyDatabase();
}
}
else
{
CopyDatabase();
}
}
private async Task<bool> CheckFileExists(string fileName)
{
try
{
var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
return true;
}
catch
{
}
return false;
}
public async void CopyDatabase()
{
StorageFile dbFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Databases/tryout2.db"));
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
await dbFile.CopyAsync(localFolder);
Categories();
}
public void Categories()
{
objConn = new SQLitePCL.SQLiteConnection("tryout2.db");
string strQ = @"SELECT * FROM DBQUIZ;";
var s = objConn.Prepare(strQ);
while (s.Step() == SQLitePCL.SQLiteResult.ROW)
{
Items.Add(new DBQUIZ(s[0].ToString(), s[1].ToString(), s[2].ToString(), s[3].ToString(),
s[4].ToString()));
}
}
public ObservableCollection<DBQUIZ> Items { get; private set; } = new ObservableCollection<DBQUIZ>();
【问题讨论】: