无法将SQLite数据库从SpeciperFolder.ApplicationData导出到SD卡Xamarin表单
我目前正在开发一个使用SQLite-NET数据库的应用程序。我正在尝试将数据库复制/导出到我的SD卡。运行代码时,我会得到 system.nullrefrenceException:'对象引用未设置为对象的实例。
我尝试了几种解决方案,但我总是得到同样的例外。这些问题发生在 system.io.file.writeallbytes(filecopyname,bytes); 请提供帮助。
private void CopyDBButton_Clicked(object sender, EventArgs e)
{
var basePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var finalPath = Path.Combine(basePath, "Mydatabase");
CopyDatabase(finalPath);
}
public static void CopyDatabase(string databasePath)
{
var bytes = System.IO.File.ReadAllBytes(databasePath);
var fileCopyName = string.Format("/sdcard/Database_{0:dd-MM-yyyy_HH-mm-ss-tt}.db", System.DateTime.Now);
System.IO.File.WriteAllBytes(fileCopyName, bytes);
}
I am currently developing an app that uses the sqlite-net database. I am trying to copy/export the database to my SD Card. When I run the code I get a System.NullRefrenceException: 'Object reference not set to an instance of an object.'
I have tried several solutions but I always get the same exception. The issues occurs at the System.IO.File.WriteAllBytes(fileCopyName, bytes); Please help.
private void CopyDBButton_Clicked(object sender, EventArgs e)
{
var basePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var finalPath = Path.Combine(basePath, "Mydatabase");
CopyDatabase(finalPath);
}
public static void CopyDatabase(string databasePath)
{
var bytes = System.IO.File.ReadAllBytes(databasePath);
var fileCopyName = string.Format("/sdcard/Database_{0:dd-MM-yyyy_HH-mm-ss-tt}.db", System.DateTime.Now);
System.IO.File.WriteAllBytes(fileCopyName, bytes);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否在清单文件中添加了下面列出的两个权限?
如果您已经确认正确添加了上述权限,请尝试使用代码将数据从应用程序存储导出到您的SD卡上:
Did you add the two permissions listed below in your manifest file?
If you have confirmed that the above permissions are correctly being added, please try the code to export data from the app storage onto your SD Card:
问题是路径地址。我通过首先检查目录以查看是否存在来修复它,然后将数据库复制到新/现有文件中的目录。我现在遇到的问题是,该文件保存到电话,而不是SD卡,但是我很高兴备份文件最终保存。
以下是代码来解决该问题:
The issue was the path address. I fixed it by checking for the directory first to see if it exists, then I copy the database to the directory in a new/existing file. The issue I have now is that the file saves to phone but not the SD card, but I am just happy that the backup file is finally saving.
Below is the code is used to fix the issue: