2016-07-22 2 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); 

Однако, это не работает, я не могу обеспечить надлежащее FilePath для моего существующий файл базы данных (он находится в корне проекта), он всегда дает мне эту ошибку:

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; 
    } 
} 
Смежные вопросы