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
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With