2016-07-22 79 views
0

我需要在Xamarin.Forms應用程序中使用預填充數據庫,因此我搜索了可能的解決方案。如何在Windows Phone 8.1中處理預填充數據庫

我找到了這個article並通過Android測試 - 它工作正常。

但是,它使用Windows Phone 8 - 與Windows 8.1不兼容。

於是,我就修改本的Windows Phone 8代號:

public static void CopyDatabaseIfNotExists(string dbPath) 
{ 
    var storageFile = IsolatedStorageFile.GetUserStoreForApplication(); 

    if (!storageFile.FileExists(dbPath)) 
    { 
    using (var resourceStream = Application.GetResourceStream(new Uri("people.db3", UriKind.Relative)).Stream) 
    { 
     using (var fileStream = storageFile.CreateFile(dbPath)) 
     { 
     byte[] readBuffer = new byte[4096]; 
     int bytes = -1; 

     while ((bytes = resourceStream.Read(readBuffer, 0, readBuffer.Length)) > 0) 
     { 
      fileStream.Write(readBuffer, 0, bytes); 
     } 
     } 
    } 
    } 
} 

進入這個代碼:

public static async void CopyDatabaseIfNotExists(string dbPath) 
{ 
    IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder; 

    StorageFile existingFile = await Windows.Storage.StorageFile.GetFileFromPathAsync("prep.db"); 
    IStorageFile storageFile = await applicationFolder.GetFileAsync(dbPath); 

    if (storageFile == null) 
    { 
    await existingFile.CopyAndReplaceAsync(storageFile); 

但是,這是行不通的,我不能提供一個適當的文件路徑我現有的數據庫文件(它在項目的根目錄),它總是給我這個錯誤:

Value does not fall within the expected range.

我怎麼能得到我的預填充文件的正確路徑?

另外,爲什麼我需要使用基於流的「複製」,當我可以簡單地複製文件本身?

+0

哪裏不給你這個錯誤(即哪一行代碼?) –

+0

@RowlandShaw當我試圖讓我的現有預填充數據庫:' StorageFile existingFile =等待Windows.Storage.StorageFile.GetFileFromPathAsync(「prep.db」);' – Nestor

回答

0

下面的代碼適用於Windows Phone的8.1和UWP:

public async void CopyDatabaseIfNotExists(string dbPath) 
{ 
    IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder; 
    var existingFile = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(myDBFileName); 

    if (!await CheckForExistingFile(myDBFileName)) 
    await existingFile.CopyAsync(applicationFolder); 
} 

private async Task<bool> CheckForExistingFile(string filePath) 
{ 
    try 
    { 
    var file = await ApplicationData.Current.LocalFolder.GetFileAsync(Uri.EscapeDataString(filePath)); 
    //no exception means file exists 
    return true; 
    } 
    catch (FileNotFoundException ex) 
    { 
    //find out through exception 
    return false; 
    } 
}