deploying winform application with embedded sqlite
Asked Answered
B

1

7

I'm deploying a winform application built with vs 2008 0n XP sp3.

I created a database with empty schema which i dropped in the root folder of the project and in properties i choosed Build Action: Embedded Resources and Copy to Output directory : Copy always. Now instead of having connectionstring in the app.config connectionString section, i put an entry in appSetting: key="database";value="mydb.db;Version=3".

So to create my connectionString i used :

 SQLiteConnection con = new SQLiteConnection("Data Source=" + Path.Combine(Application.StartupPath, ConfigurationManager.AppSettings["database"]));

Everything works fine and i packaged the app with a setup project.Now after i installed the app the database could not be found and i was obliged to copy the database to the Application Folder in the setup project for it to work.

what i thought is that db is supposed to be in the app dll because of copy always .but i can't access it.So what exactly did i do wrong?

i'm suspecting i should have just connected to the root db meaning not using Application.StartupPath

But i'm here asking for the best practices cause what i did is working but still looking like workaround so please can anyone share his experience with me? thanks for reading

Blen answered 22/4, 2010 at 9:32 Comment(2)
I guess this is more of a "embedding a file" question than an SQLite question.Paternity
yes it is.but then sqlite is one of the most embedded database so majority of those who use sqlite might know about embedding a database.correct?Blen
A
5

Embedded Resource means the database gets embedded in your dll. The Copy to output directory setting doesn't apply in this case, that's used for Build Action: Content.

With the database embedded, you basically have to un-embed it on first use. To do this read it out of the Assembly and store it to a file.

class EmbeddedResourceTest
{
    public static void Test()
    {
        string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Test.db");

        using(var resourceStream = typeof(EmbeddedResourceTest).Assembly.GetManifestResourceStream("Test.db"))
        {
            using(var fileStream = File.OpenWrite(path))
            {
                CopyStream(resourceStream, fileStream);
            }
        }

        // now access database using 'path'
    }

    public static void CopyStream(Stream inputStream, Stream outputStream)
    {
        CopyStream(inputStream, outputStream, 4096);
    }

    public static void CopyStream(Stream inputStream, Stream outputStream, int bufferLength)
    {
        var buffer = new byte[bufferLength];
        int bytesRead;
        while ((bytesRead = inputStream.Read(buffer, 0, bufferLength)) > 0)
        {
            outputStream.Write(buffer, 0, bytesRead);
        }
    }
}
Audiogenic answered 23/4, 2010 at 3:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.