2016-08-27 1 views
0

У меня есть вопрос о форме Xamarin.Как я могу узнать относительный путь ресурса внутри портативной библиотеки Xamarin Forms?

Я разрабатываю свое первое кросс-платформенное приложение (iOS и Android), и я решил создать решение формы приложения.

Мое приложение должно использовать базу данных SQLite, которая загружается при запуске приложения с FTP-сервера. Если сервер недоступен, приложение должно использовать локальную базу данных SQLite, которую я вставляю в переносимую библиотеку.

Для этого я создал папку внутри переносной библиотеки, и я поместил в нее файлы SQLite. (Это правильно? Или мне нужно поставить проект iOS/Android?)

Чтобы строка подключения к этой локальной базе данных мне нужно знать ее путь. Откуда мне знать?

спасибо!

ответ

0

, чтобы сделать это, вы должны реализовать интерфейс по общему проекту, который будет иметь только один раз способом, чтобы получить соединение в зависимости от пути на каждом устройстве, как показано ниже:

public interface ISQLite 
{ 
    SQLiteConnection GetConnection(); 
} 

и реализовать этот интерфейс по каждому проекту -для Android:

[assembly: Dependency (typeof (SQLite_Android))] 

namespace GenYouth.Droid 
{ 
    public class SQLite_Android : ISQLite 
    { 
     public SQLite_Android() 
     { 
     } 

     #region ISQLite implementation 
     public SQLite.SQLiteConnection GetConnection() 
     { 
      var sqliteFilename = "db_Name.db3"; 
      string documentsPath = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal); // Documents folder 
      var path = Path.Combine(documentsPath, sqliteFilename); 

      // This is where we copy in the prepopulated database 
      Console.WriteLine (path); 
      if (!File.Exists(path)) 
      { 
      /* 
      var s = Forms.Context.Resources.OpenRawResource(Resource.Raw.GenYouth_db); // RESOURCE NAME ### 

      // create a write stream 
      FileStream writeStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write); 
      // write to the stream 
      ReadWriteStream(s, writeStream); 
      * */ 
     } 

     var conn = new SQLite.SQLiteConnection(path); 

     // Return the database connection 
     return conn; 
    } 
    #endregion 

    /// <summary> 
    /// helper method to get the database out of /raw/ and into the user filesystem 
    /// </summary> 
    void ReadWriteStream(Stream readStream, Stream writeStream) 
    { 
     int Length = 256; 
     Byte[] buffer = new Byte[Length]; 
     int bytesRead = readStream.Read(buffer, 0, Length); 
     // write the required bytes 
     while (bytesRead > 0) 
     { 
      writeStream.Write(buffer, 0, bytesRead); 
      bytesRead = readStream.Read(buffer, 0, Length); 
     } 
     readStream.Close(); 
     writeStream.Close(); 
    } 
} 

}

для IOS:

 [assembly: Dependency (typeof (SQLite_iOS))] 

namespace GenYouth.iOS 
{ 
    public class SQLite_iOS : ISQLite 
    { 
     public SQLite_iOS() 
     { 
     } 

     #region ISQLite implementation 
     public SQLite.SQLiteConnection GetConnection() 
     { 
      var sqliteFilename = "db_Name.db3"; 
      string documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal); // Documents folder 
      string libraryPath = Path.Combine (documentsPath, "..", "Library"); // Library folder 
      var path = Path.Combine(libraryPath, sqliteFilename); 

      // This is where we copy in the prepopulated database 
      Console.WriteLine (path); 
      if (!File.Exists (path)) { 
       File.Copy (sqliteFilename, path); 
      } 

     var conn = new SQLite.SQLiteConnection(path); 

     // Return the database connection 
     return conn; 
    } 
    #endregion 
} 

 Смежные вопросы

  • Нет связанных вопросов^_^