I am learning data directory and I have discovered and learnt a lot of people seemed to ask similar questions for example: here, here, here and here. There is one thing that is troubling me. That is once the application has been deployed can the user change the location for there database? For example I am testing my application and the database is stored in bin/Debug folder. I moved the database file to a temp folder so its in C:\A\database1.mdb. When I run the application I received the an error of...
Could not find file 'C:\...\bin\Debug\database1.mdb'.
1) Why do I have to put the db file in bin/Debug folder?
2) How do I overcome the problem for the application to read and access file in C:\A\database1.mdb when I use Data Directory (relative path) instead of hard code?
As repeated above
3) That is once the application has been deployed can the user change the location for there database?
.cs files and .config for Build Action I have selected Compile and for Copy to Output Directory I have selected Copy always
I have a connectionstring that looks like this...
myCon = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= |DataDirectory|\database1.mdb");
I have App.config file and it looks like this...
<connectionStrings>
<add name="Project1.Properties.Settings.Project1ConnectionString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\database1.mdb" providerName="System.Data.OleDb"/>
</connectionStrings>
As example
public MainForm()
{
InitializeComponent();
this.WindowState = FormWindowState.Maximized;
myCon = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\database1.mdb");
}
OleDbConnection myCon;
OleDbCommand cmd;
private void btnInsert_Click(object sender, EventArgs e)
{
myCon.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = myCon;
OleDbCommand cmdCheck = new OleDbCommand();
cmdCheck.Connection = myCon;
cmdCheck.CommandText = "SELECT COUNT(*) FROM Details WHERE ID = ?";
cmdCheck.Parameters.AddWithValue("@ID", txtID.Text);
if (Convert.ToInt32(cmdCheck.ExecuteScalar()) == 0)
{
cmd.CommandText = (@"INSERT INTO Details (ID, FirstName)
VALUES(@ID, @FirstName)")
cmd.Parameters.AddWithValue("@ID", txtID.Text);
cmd.Parameters.AddWithValue("@FirstName", txtFirstName.Text);
cmd.ExecuteNonQuery();
}
myCon.Close();
}
Thanks in advance if anyone can guide me here.