Reputation: 3274
I created a project where I'm trying to copy to local files in Xamarin.Forms, one is an XML and one is a local DB in SQLite:
I configured them as EmbeddedResources. I tried to access their current location using this:
public static class Constants
{
public const string DatabaseFilename = "savethatpower.db";
public const SQLite.SQLiteOpenFlags Flags =
// open the database in read/write mode
SQLite.SQLiteOpenFlags.ReadWrite |
// create the database if it doesn't exist
SQLite.SQLiteOpenFlags.Create |
// enable multi-threaded database access
SQLite.SQLiteOpenFlags.SharedCache;
public static string DatabasePath
{
get
{
var basePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
return Path.Combine(basePath, DatabaseFilename);
}
}
}
public void CopyFiles(string name) {
var localPath = $"{Application.Current.Resources.Source.AbsolutePath}/{name}";
File.Copy(localPath, Constants.DatabasePath);
}
CopyFiles("savethatpower.db");
CopyFiles("dbInfo.xml");
This line provides me a tricky bug since the beginning: var localPath = $"{Application.Current.Resources.Source.AbsolutePath}/{name}";
InnerException {System.NullReferenceException: Object reference not set to an instance of an object at SaveThatPower.Classes.XML.XML2CSharp..ctor (System.String name) [0x00008] in /Users/fanmixco/Documents/GitHub/SaveThatPower/SaveThatPower/SaveThatPower/Classes/XML/XML2CSh…} System.NullReferenceException
I found that the Source
is null
but I don't know how to access its current location. I also tried directly accessing the files like this:
File.Copy("dbVersion.xml", Constants.DatabasePath);
But nothing happened. I'm wondering, do you know what is the correct way to copy files? Thanks.
Upvotes: 0
Views: 186
Reputation: 24470
Files marked as EmbeddedResource will be accessible through the Assembly. You will need to do something like:
var assembly = this.GetType().Assembly;
using var databaseStream = assembly.GetManifestResourceStream("My.Assembly.Namespace.my_database_file.db");
using var fileStream = File.Open(localPath, FileMode.CreateNew);
await databaseStream.CopyToAsync(fileStream);
Upvotes: 1