Opening Access Database with C# - c#

I have this connection string :
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\Release\DB.accdb"); // Database Connection
I want my program to connect to the database without the "..\Release\" in the string.
What I mean is, that i want the program to look for the database in the program's folder, without specifying the folder's name (whatever the folder's name is).
How is that done?

You should add your DB to the project (Add -> Existing Item...) and set Build Action to Content and Copy to Output Directory to Copy always:
After that you can using following connection string:
string cs = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=test.mdb;Persist Security Info=False;";
Following code, will find database file in program folder or sub-folder:
string programPath = System.IO.Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName;
var dbPath = System.IO.Directory.GetFiles(programPath, "*.accdb", SearchOption.AllDirectories).FirstOrDefault();
string cs = null;
if (!string.IsNullOrEmpty(dbPath))
{
cs = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Persist Security Info=False;", dbPath);
}

Perhaps you could use something like
String strAppDir = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
String strFullPathToMyFile = System.IO.Path.Combine(strAppDir, "DB.accdb");
ref:
How to: Get the Application Directory

Related

Local Database after publishing C#

i'm trying to make is so my program can have a local database after i have published it. Now i want it to work so i can install in on any computer so i have to change my connection string but i can't seem to figure out to what to change it to this is my connection string i have now
string constring = "Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = \"C:\\Barcode\\Application Files\\Barcode Scanning_1_0_0_0\\BarcodeDB.mdf\"; Integrated Security = True";
Before publishing i have went into applicationfiles and made sure that BarcodeDB.mdf is included but from what i've seen it changes to BarcodeDB.mdf.deploy after i've published it.
I've also went into Prerquisites and added
SQL Server 2012 Express LocalDB
When i try to run the published program or the debugger with the code i have now i get the error:
An attempt to attach an auto-named database for file C:\Barcode\Application Files\Barcode Scanning_1_0_0_0\BarcodeDB.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share
I'm guessing i need to use:
| DataDirectory |
But i'm new to all of this so i can't seem to figure it out how to use it even after searching for it so i would deeply appreciate it if someone could be kind to eiter explain how i chould be using DataDirectory or if i'm wrong and should be using something else.
And also sorry if i structured this question badly trying to get better at it
Best Regards Hannes.
Edit 1: Here is the code where i try to connect and using the database
string constring = $"Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = \"{Application.ExecutablePath.ToString()}\\Application Files\\Barcode Scanning_1_0_0_0\\BarcodeDB.mdf\"; Integrated Security = True";
string Query = "SELECT Name FROM Products ORDER BY EDate;";
SqlConnection conDataBase = new SqlConnection(constring);
SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase);
SqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string sName = myReader.GetString(myReader.GetOrdinal("Name"));
cbxProducts.Items.Add(sName);
cbxProducts.Sorted = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Ok I assume that your project is a Windows Forms or WPF project if it's not please tell me.
Your problem is that you are hard-coding a path to a database file which may not exist or your process can't have access to it's location. What you have found as | DataDirectory | is to use in web projects Web.Config file which will be mapped to App_Data folder.
In your case you have to build the connection string using your own applications executable path. Try this code:
//WPF:
string constring = $"Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = \"{System.Reflection.Assembly.GetExecutingAssembly().Location}\\BarcodeDB.mdf\"; Integrated Security = True";
//Windows Forms:
string constring = $"Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = \"{Application.ExecutablePath.ToString()}\\BarcodeDB.mdf\"; Integrated Security = True";
string constring = $"Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=" + Directory.GetCurrentDirectory().ToString() + "\\BarcodeDB.mdf;Integrated Security=True";
This fixed it for me

Sqlite c# creates 2 same named databases

I have a problem that when i want to create database and specify its name it is created in the specified directory and in directory where the aplication is running. Why is that happening?
Code that creates database:
using System.Data.SQLite;
...
private static string AddDb(string dbName, string dbPassword)
{
try
{
//default paths
string startupPath = Environment.CurrentDirectory;
string dataBasePath = startupPath + "\\DB\\" + dbName;
//creating the dbfile
SQLiteConnection.CreateFile(dataBasePath);
//Opening connection
SQLiteConnection dbConnString;
dbConnString = new SQLiteConnection("Data Source =" + dbName + ";Version=3;");
dbConnString.Open();
dbConnString.ChangePassword(dbPassword);
dbConnString.Close();
return dataBasePath;
}
catch
{
MessageBox.Show("Failed to create database", "DB Creator");
return "";
}
}
The problem seems to be that you use different paths in CreateFile and your connection string.
If you look at your code below you'll notice that in one case you use a full path to create the file (databaseBasePath), while in the other case you only use the database file name in your connection string (dbName). Without an absolute path, this may be a different folder!
string dataBasePath = startupPath + "\\DB\\" + dbName;
SQLiteConnection.CreateFile(dataBasePath);
SQLiteConnection dbConnString;
dbConnString = new SQLiteConnection("Data Source =" + dbName + ";Version=3;");
It seems like Open then creates the file if it can't find it.
A word on the paths:
You're not allowed to write the Program Files folder, so using the current folder for the database file is really a bad idea.
The use of Environment.CurrentDirectory is also a bad idea. Depending on how you start your application, this may or may not be the folder that you think it is (see my comments to the other answers and this).
Never assume that \ is actually the path separator. Use Path.Combine instead.
I suggest that you use Environment.GetFolderPath to get a location that's shared among all users (if the database content should be shared) or private to the current user (if all users should have their own database) and create the database there:
string baseFolder = Environment.GetFolderPath(<wherever it should be>);
string dataBasePath = Path.Combine(baseFolder, "DB", dbName);
SQLiteConnection.CreateFile(dataBasePath);
SQLiteConnection dbConnString = new SQLiteConnection(String.Format("Data Source = {0};Version=3;", dataBasePath);
The Environment.CurrentDirectory contains the directory that the application starts from by default. You can set this property. See the MSDN article Environment.CurrentDirectory Property

C# set desktop path for database

I have created a project in visual studio, that uses a database to store and retrieve details.
I want to deliver an executable and just let the user know that he has to place the database file on the desktop.
if i do
String myDesktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
it looks like i cant set the database position after like this:
using (SqlCeConnection cn = new SqlCeConnection(#"Data Source = myDesktop\Database1.sdf))
Any help?
Form a correct path using the Path.Combine method of the Path class
string conString = "Data Source=" + Path.Combine(myDesktop, "Database1.sdf;");
using (SqlCeConnection cn = new SqlCeConnection(conString))

OleDb connection to Access 2013 database

I have a program that reads from and writes to an Access database. It works fine on my own computer but when I tried to download it on a new computer that has the new Office 2013 programs it said that the provider in connection string didn't work. Here's my connection string:
string filepath = #"C:\FamilyFoundations\ProvidentLiving\App\Data\"; // Hold the path to the file
string dbPath = filepath + "GoalsDB.accdb"; // Holds the name of our data base
// string to create our database
string db = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + dbPath + "; JET OLEDB:Engine Type=5";'
Does my string need to be changed or is there something I need to download on my friends computer? My first thought is that there is a new Microsoft.JET that I need to include, but please correct me if I'm wrong.

C# - Get file path from connection string

Is there an existing method in C# to extract the file path from a string that represents a ConnectionString to a SqlCE .sdf file? I want to check if the file exists at initialization and back it up if the file has been modified.
Sample connection string:
strConn = "Data Source=|DataDirectory|\dbAlias.sdf";
You can use SqlCeConnectionStringBuilder class to parse existing Sql Compact connection string.
A bit late perhaps, but I came across this question wile struggling with the same problem. You can find the location of the |DataDirectory| folder with AppDomain.CurrentDomain.GetData("DataDirectory"). So your connectionstring can be translated like this:
strConn .Replace("|DataDirectory|", AppDomain.CurrentDomain.GetData("DataDirectory").ToString())
You could just create the connection and get the data source from it as a property:
string data;
using (var conn = new SqlConnection(connectionString)) {
data = conn.DataSource;
}
For LocalDB and SqlConnection (not CE):
public static string GetFilePathFromConnectionString(string connectionString)
{
var attachDbFileName = new SqlConnectionStringBuilder(connectionString).AttachDBFilename;
return attachDbFileName.Replace("|DataDirectory|", AppDomain.CurrentDomain.GetData("DataDirectory").ToString());
}

Categories