質問

私はモノドロイドアプリを持っています。 sqliteデータベースに接続するために、mono.data.sqliteおよびsytem.dataを使用します。データベースをプログラムで作成すると、正常に実行されますが、データベース「test.db」をAssetsフォルダーに配置してコピーしようとすると、FilenotFoundExceptionが表示されます。以下は、データベースをコピーしてから接続するために使用するコードです。

 public class Activity1 : Activity
{
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        TextView tv = new TextView(this);
        string dbPath = Path.Combine(
        System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),
        "test.db");

        bool exists = File.Exists(dbPath);
        if (!exists)
            SqliteConnection.CreateFile(dbPath);
        var connection = new SqliteConnection("Data Source=" + dbPath);
        connection.Open();
        if (!exists)
        {
            Stream myInput = Assets.Open("test.db");
            String outFileName = dbPath + "test.db";
            Stream myOutput = new FileStream(outFileName, FileMode.OpenOrCreate);

            byte[] buffer = new byte[1024];
            int b = buffer.Length;
            int length;
            while ((length = myInput.Read(buffer, 0, b)) > 0)
            {
                myOutput.Write(buffer, 0, length);
            }

            myOutput.Flush();
            myOutput.Close();
            myInput.Close();
        }

        using (var contents = connection.CreateCommand())
        {
            contents.CommandText = "SELECT [Field1], [Field2] from [Table]";
            var r = contents.ExecuteReader();
            while (r.Read())
                tv.Text += string.Format("\n\tField1={0}; Field2={1}",
                        r["Field1"].ToString(), r["Field2"].ToString());
        }
        connection.Close();


        SetContentView(tv);
   }
}

}

役に立ちましたか?

解決

一見、私はここでいくつかの可能な問題を見ます:

  1. Assetsフォルダー内のファイルのビルドアクションはAndroidAssetに設定されていますか?
  2. ファイルが存在しない場合、dbpath + "test.db"に書いていますが、dbpathにはすでにファイル名が含まれています
  3. 接続を作成および開く前に、ファイルを確認/作成することをお勧めします
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top