我一直在尝试向我的应用添加备份/还原选项,因此我搜索并找到了一些有用的信息(这似乎很容易做到)。
其中一个与File
中的Xamarin.Essentials
有关,我曾尝试使用,但一直给我一个“访问被拒绝”错误。
获取数据库目录:
public Restaurar()
{
InitializeComponent();
localPath = Path.Combine(FileSystem.AppDataDirectory, templateFileName);
}
原始文件和备份名称以及localpath
:
const string templateFileName = "database.sqlite";
const string localFileName = "backup_database.sqlite";
string localPath;
创建备份的功能:
private void BtnBackup_Clicked(object sender, EventArgs e)
{
var reading = File.ReadAllText(localPath);
File.WriteAllText(localFileName, reading);
DisplayAlert("BACKUP", "Backup file created!", "OK");
}
将备份文件移动到另一个数据库文件夹中:
private void BtnMove_Clicked(object sender, EventArgs e)
{
File.Move(localFileName, FileSystem.AppDataDirectory);
}
单击“备份”按钮时出现以下异常:
System.UnauthorizedAccessException: 'Access to the path "/backup_database.sqlite" is denied.'
然后单击“移动”按钮:
System.IO.FileNotFoundException: 'Could not find file'/backup_database.sqlite'.'
我认为这将在项目文件夹上创建一个新文件,使我能够移动android / IOS数据库文件夹。感谢您的帮助,谢谢!
编辑:
我尝试了另一种方法:
我已经有了DependecyService来获取平台特定于数据库的路径,因此我使用了它。
备份:
private void BtnBackup_Clicked(object sender, EventArgs e)
{
var dep = DependencyService.Get<IPath>();
string db_path = dep.GetPath("database.sqlite");
string backup_path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData));
var origin = File.ReadAllBytes(db_path);
File.WriteAllBytes(backup_path, origin);
DisplayAlert("BACKUP", "Backup created!", "OK");
}
还原:
private void BtnRestaurar_Clicked(object sender, EventArgs e)
{
var dep = DependencyService.Get<IPath>();
string db_path = dep.GetPath("database.sqlite");
string backup_path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData));
var origin = File.ReadAllBytes(backup_path);
File.WriteAllBytes(db_path, origin);
DisplayAlert("RESTAURING", "Backup restored!", "OK");
}
我得到以下提示:
System.UnauthorizedAccessException: 'Access to the path '/data/user/0/com.companyname.VendasEstoque/files/.local/share' is denied.'