如何在Windows Phone 8.1中处理预填充数据库

时间:2016-07-22 12:24:26

标签: c# windows-phone-8 windows-phone-8.1 xamarin.forms

我需要在我的Xamarin.Forms应用程序中使用预先填充的数据库,因此我搜索了可能的解决方案。

我发现这个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);

但是,它不起作用,我无法为我现有的db文件提供正确的文件路径(它位于项目的根目录中),它总是给我这个错误:

  

价值不在预期范围内。

我怎样才能获得预先填充文件的正确路径?

另外,为什么我只需复制文件本身就需要使用基于流的“复制”?

1 个答案:

答案 0 :(得分: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;
  }
}