Search code examples
c#blazormauisqlite-net-pcl

File Created by File.WriteAllBytes() Doesn't Persist After Program Ends


I followed an old sqlite-net-pcl tutorial (if you're curious) that used this code to copy an Embedded Resource into an external file it should create in C://Users/my user/AppData/Local. I confirmed the database itself was copied correctly with the GetObject function and that the filepath was where I thought it was, but once the program finishes running, there is no new file there. Am I just fundamentally misunderstanding what is going on?

MainPage.xaml.cs:

using System.Collections.ObjectModel;
using System.Reflection;
using TestApp.Models;

namespace TestApp
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();

            var assembly = IntrospectionExtensions.GetTypeInfo(typeof(App)).Assembly;
            using (Stream stream = assembly.GetManifestResourceStream("TestApp.Inventory.db"))
            {
                using (MemoryStream MemStr = new MemoryStream())
                {
                    stream.CopyTo(MemStr);
                    File.WriteAllBytes(ObjectRepository.DbPath, MemStr.ToArray());
                }
            }

            ObjectRepository repository = new ObjectRepository();
            foreach (var object in repository.List())
            {
                Objects.Add(object);
            }
         }
    }
}

ObjectRepository.cs:

using System.Reflection;
using TestApp.Models;

namespace TestApp.Data
{
    public class ObjectRepository
    {
        private readonly SQLiteConnection _Database;

        public static string DbPath { get; } = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Inventory.db");

        public ObjectRepository()
        {
            _Database = new SQLiteConnection(DbPath);
            _Database.CreateTable<Object>();
        }
        public Object GetObject(string ObjectNumber)
        {
            return _Database.FindWithQuery<Object>("select * from Objects where ObjectNumber = ?", [ObjectNumber]);
        }
    }
}

The Object class in TestApp/Models/Object.cs:

using SQLite;

namespace TestApp.Models
{
    [Table("Objects")]
    public class Object
    {
        [PrimaryKey]
        public string ObjectNumber { get; set; } = string.Empty;
    }
}

Solution

  • The simple answer is that the file actually was being created, just not where I thought it was based on the used file path.

    Saving directly in the AppData/Local folder seems to not be possible, and when checking where a file ends up, checking the base path alone fed into the File object does not guarantee filepath accuracy.