我正在尝试在 Xamarin Forms 应用程序中使用 LiteDB,但是我似乎无法获得对文件的写入或读取权限。
从我的 MainViewModel.cs 调用
我已将权限添加到 AndroidManifest.xml;
<uses-sdk android:minSdkVersion="23" android:targetSdkVersion="25" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_LOGS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_USER_DICTIONARY" />
<uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.READ_SOCIAL_STREAM" />
<uses-permission android:name="android.permission.READ_SYNC_STATS" />
<uses-permission android:name="android.permission.REBOOT" />
<uses-permission android:name="android.permission.RESTART_PACKAGES" />
<uses-permission android:name="android.permission.SET_ORIENTATION" />
<uses-permission android:name="android.permission.SET_DEBUG_APP" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_PROFILE" />
<uses-permission android:name="android.permission.WRITE_GSERVICES" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
我在 Android 6.0 中为我的应用程序添加了权限;
更新:我检查了路径访问,并且可以写出文件。
string documentsPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var dirPath = documentsPath + "/MyTestFolder";
var exists = Directory.Exists(dirPath);
var filepath = dirPath + "/test.txt";
if (!exists)
{
Directory.CreateDirectory(dirPath);
if (!System.IO.File.Exists(filepath))
{
var newfile = new Java.IO.File(dirPath, "test.txt");
using (FileOutputStream outfile = new FileOutputStream(newfile))
{
string line = "The very first line!";
outfile.Write(System.Text.Encoding.ASCII.GetBytes(line));
outfile.Close();
}
}
}
然而,这段代码失败了;
string documentsPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var dirPath = documentsPath + "/MyData/MyDB.db";
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
using (var db = new LiteDatabase(dirPath))
{
// Get customer collection
var collection = db.GetCollection<T>(typeof(T).Name);
collection.Insert(tobj);
return true;
}