Reputation: 11
How can I create an Access database when my .NET Windows application runs for the first time? I want to create a database with tables used in my project when I install my .exe on a client machine, ask the path for db and create db used in my application.
Upvotes: 0
Views: 883
Reputation: 123409
From the asker's comment to the question
is there any suggestion to create all the tables with db automatically used in my application or I have to crate tables programmatically using c# code
If you want to avoid writing all of the DDL code (CREATE TABLE, CREATE INDEX, ...) to create the table structures "from scratch" you could create the database and all of the tables, etc., in Access. Then you could add that "blank" database file (table structures but no data) as a Resource in your .NET project.
When your application launches it can check for the existence of a local (non-"blank") copy of the database. If one doesn't exist then it can copy the "blank" database from the application's Resources to the desired location on the hard drive.
For example, if I create a "blank" database named "resTestData.accdb" and save it as a File
Resource in my project I can copy it to the local hard drive like so:
string persistentDbLocation = @"C:\Users\Gord\Desktop\resTestUserData.accdb";
if (File.Exists(persistentDbLocation))
{
Console.WriteLine("Local persistent copy of database already exists.");
}
else
{
// "resTest" is the name I gave to my C# Project, hence resTest.Properties
byte[] dbResource = resTest.Properties.Resources.resTestData; // .accdb File Resource
using (FileStream output = new FileStream(persistentDbLocation, FileMode.Create, FileAccess.Write))
{
output.Write(dbResource, 0, dbResource.Length);
}
Console.WriteLine("Local persistent copy of database saved to \"{0}\".", persistentDbLocation);
}
Upvotes: 2