Connection string to access database in Program files - c#

I am working on windows form which uses microsoft access database.
When the application will be installed, the database will be on this location
C:\Program Files (x86)\Amrit\trial\Database.
How can i make this work so that this application will linked to the database when installed in my computer.
Can somebody give me easy solution..
Currently my connection string looks like this..
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Amrit\\Desktop\\Database.accdb ;Persist Security Info=False;";
when i create setup file for appplication, the database will be in ProgramFiles/AmritCreations/AppName/Database.accdb

Just place your database and your application in the same directory and use this connectionString
string connString = "Provider=MICROSOFT.ACE.OLEDB.12.0; " +
"Data Source=|DataDirectory|/Database.accdb";
In times you're creating a Setup Project, try to place the database file and [yourProjectName].exe in the same directory.

Related

Set the connection string to the path of the database dynamically [duplicate]

I am using SQL Express databases as part of a unit test project in c#. My databases is located here:
./Databases/MyUnitTestDB.mdf
I would like to use a relative path or variable in the app.config rather than having my connection string defined as:
AttachDbFilename=C:\blah\blah\blah\yea\yea\yea\MyApplication\Databases\MyUnitTestDB.mdf
I have seen the use of |DataDirectory| but am I correct in thinking this is only applicable to web applications?
I want to control this in the application configuration file, as in production the application uses a hosted sql database.
Thanks everyone, I used a combination of your responses.
In my app.config file my connection string is defined as follows
<add name="MyConnectionString"
connectionString="Server=.\SQLExpress;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Database=MyDatabaseForTesting;Trusted_Connection=Yes;" />
In my unit test class I set the DataDirectory property using the following
[TestInitialize]
public void TestInitialize()
{
AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Databases"));
// rest of initialize implementation ...
}
Yes, |DataDirectory| Web application to select the App_Data directory of the web application.
In a not web application, depending on .NET Framework, it could be used and also changed using AppDomain.SetData
But you have other two posiblities to create the connection:
1.- Use a relative path:
String con ="... AttachDbFilename=Databases\MyUnitTestDB.mdf ... ";
2.- get the application path and add to the String.
In c# Windows Application you can use Application.StartupPath
String con= " ... AttachDbFilename=" + Application.StartupPath + "\Databases\MyUnitTestDB.mdf ... ";
Depending on the applicaiton type or launch mode you got different properties. Ex:
Application.StartupPath -- The start path of the exe application that starts the application
Application.ExecutablePath -- the start path an name of the exe application that stats the application
But to use Application you need to include System.Windows.Forms that is not included for example into console applications.
System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) -- This gets the path from the current assembly "dll,exe,..." Is not affected by application type, path changes,... Always return the directory when the Assemby resides.
Environment.CurrentDirectory -- the current directory. This can be changed for example if you navigate into folders.
You can find more about the different connection string options here
http://www.connectionstrings.com/sql-server-2005
I have spent a whole day googling to work this through and finally have a clue from this
Here is my solution:
1. Use |DataDirectory| in connection string
<add name="NorthwindConnectionString" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDbFilename=|DataDirectory|\Northwind.mdf;User Instance=True" providerName="System.Data.SqlClient" />
2.Set DataDirectory in ClassInitialize
[ClassInitialize()]
public static void MyClassInitialize(TestContext testContext)
{
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
int index = baseDir.IndexOf("TestResults");
string dataDir = baseDir.Substring(0, index) + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
AppDomain.CurrentDomain.SetData("DataDirectory", dataDir);
}
I'm building a simple Windows Forms App with VS2010 with C#3.0. Also using SQL Express 2008 RC2.
I am able to use: |DataDirectory|MyDb.mdf in the connection string alone without changing anything else. The |DataDirectory| points to the location of my .exe file.
I will think that this would be the first thing all of you would try, so that is why I'm specifying my VS and SQL version. Or maybe it is new to C#3.0.
My complete Connection String:
"Server=.\SQLExpress;AttachDbFilename=|DataDirectory|App_Data\ThumbsUpPlayer.mdf;Database=ThumbsUpPlayer;Trusted_Connection=Yes;"
Note that I have added a "App_Data" folder to my application, because I'm used to the Db in that folder, the folder is not recognised by VS.
I don't have Visual Studio here, but what about:
using System.IO;
using System.Windows.Forms;
string appPath = Path.GetDirectoryName(Application.ExecutablePath);
AttachDBFilme = appPath + "\\MyUnitTestDB.mdf"
I did the following. Hopefully it helps someone.
AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory + "../../App_Data"));
Dynamic Path in SQL Server Connection
SqlConnection con="Server=.\SQLExpress;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Database=MyDatabaseForTesting;Trusted_Connection=Yes;" ;

"Unable to open the database file". Do I have to put the full physical location of sqlite database when developing C# Console application

I have created a Sqlite database mydatabase.sqlite and placed it in my App_Data folder inside the console application project. I am getting an error:
Unable to open the database file
when developing a console application using sqlite and C#.
When I am using
string cs = #"Data Source=App_Data\mydatabase.sqlite;Version=3";
I am getting
Unable to open the database file error;
But when I am using
string cs = #"Data Source=C:\Users\UP_SW02\Desktop\ConsoleApplication1\ConsoleApplication1\App_Data\mydatabase.sqlite;Version=3";
The application is running properly.
Is there any possibility to use Sqlite Data Source not using full physical location?
Thank you..
All non-rooted paths used inside a program are relative to the folder in which the application is started. Note that this is not necessarily the folder that the application itself is in. You have to be very careful with such paths.
What you seem to be after is the folder relative to your own application. There's a simple method for getting that. If you have the Windows.Forms namespace included in your project, you can get the executable's path from System.Windows.Forms.Application.ExecutablePath:
// Get app folder
String appFolder = Path.GetDirectoryName(Application.ExecutablePath)
// Combine with sqlite db path
String dbPath = Path.Combine(appFolder, #"App_Data\mydatabase.sqlite");
// Build connection string
string cs = String.Format(#"Data Source={0};Version={1}", dbPath, 3);
An alternative for Application.ExecutablePath if you're not using a Windows forms program is Assembly.GetExecutingAssembly().Location, from the System.Reflection namespace.
The simplest way to get folder's relative path in a connection string is to simply add |DataDirectory|.
before
string cs = #"Data Source=App_Data\mydatabase.sqlite;Version=3";
after
string cs = #"DataSource=|DataDirectory|\App_Data\mydatabase.sqlite;Version=3";
No there is no way SQlite needs to full path address but you can resolve it with two solutions:
1- Save connection path in config file.
2- Get App_Data folder path by GetFolderPath method like:
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
So your code would be like:
var fileName = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.ApplicationData), "mydatabase.sqlite");
string sqliteConnection = string.Format("Data Source={0};Version=3;Timeout=2;", fileName);
3- Or the easy way is :
string sqlitePath = Directory.GetCurrentDirectory() + "/App_Data/mydatabase.sqlite";

Release a WPF app with local database

OK, so I am quite lost. This is my first real application written for windows with a local database.
I have written an WPF application in VS2012 with a local database, which has all CRUD written as stored procedures.
The app is working as I run it in VS. But as I build the app and install it (on any machine) the database is not accessible. I have a feeling the connection string is causing this issue.
First I used this connection string:
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename='D:\LH\Personalitytest win\DB.mdf';Integrated Security=True;Database=DB")
But as I got "Error: 26 – Error Locating Server/Instance Specified" I guessed that the Data Source of the connection is not correct (although the AttachDbFilename is definitly incorrect). So, I changed the connection string to:
SqlConnection conn = new SqlConnection(#"Server=(localdb)\v11.0;AttachDbFilename=" + AppDomain.CurrentDomain.BaseDirectory + "DB.mdf;Database=DB;Trusted_Connection=Yes;");
And I got an error which basically said that the file DB.mdf is not found.
So, I made sure that the .mdf and .ldf files are copied to the installation directory/database.
But after installation both these files are read only (even if these have read/write persmission as I am developing). I have tried to change the file permissions (for both files) as the application starts for the first time by:
string path = AppDomain.CurrentDomain.BaseDirectory + #"Database\DB.mdf";
FileInfo file = new FileInfo(path);
file.IsReadOnly = false;
and
File.SetAttributes(path, FileAttributes.Normal);
and
FileAttributes attributes = File.GetAttributes(path);
attributes = attributes & ~FileAttributes.ReadOnly;
File.SetAttributes(path, attributes);
but neither of these methods are working.
My question is basically, how should the database be implemented in the final release?
Your database should be located in your windows user directory
Other way is to install SqlServer Express on your machine. And configure your connection string accordingly.

Access DB connected with local directory

Basically I want the connection of my Access DB always available, so if i move the folder project to another computer it has to keep working, without changing the folder path.
I'm working with Windows Forms in Visual Studio 2012.
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data source= Z:\Tempesta\Area Progetto\Area_Progetto_27_02_2014\Area_Progetto_DATA_MAGAZINE\Data_Magazine\Data_Magazine\DB\DataMG.mdb";
That's the code I have right now for the connection to the DB.
Try this
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0; Data
Source=|DataDirectory|DataMG.mdb"

SQL Express connection string: mdf file location relative to application location

I am using SQL Express databases as part of a unit test project in c#. My databases is located here:
./Databases/MyUnitTestDB.mdf
I would like to use a relative path or variable in the app.config rather than having my connection string defined as:
AttachDbFilename=C:\blah\blah\blah\yea\yea\yea\MyApplication\Databases\MyUnitTestDB.mdf
I have seen the use of |DataDirectory| but am I correct in thinking this is only applicable to web applications?
I want to control this in the application configuration file, as in production the application uses a hosted sql database.
Thanks everyone, I used a combination of your responses.
In my app.config file my connection string is defined as follows
<add name="MyConnectionString"
connectionString="Server=.\SQLExpress;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Database=MyDatabaseForTesting;Trusted_Connection=Yes;" />
In my unit test class I set the DataDirectory property using the following
[TestInitialize]
public void TestInitialize()
{
AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Databases"));
// rest of initialize implementation ...
}
Yes, |DataDirectory| Web application to select the App_Data directory of the web application.
In a not web application, depending on .NET Framework, it could be used and also changed using AppDomain.SetData
But you have other two posiblities to create the connection:
1.- Use a relative path:
String con ="... AttachDbFilename=Databases\MyUnitTestDB.mdf ... ";
2.- get the application path and add to the String.
In c# Windows Application you can use Application.StartupPath
String con= " ... AttachDbFilename=" + Application.StartupPath + "\Databases\MyUnitTestDB.mdf ... ";
Depending on the applicaiton type or launch mode you got different properties. Ex:
Application.StartupPath -- The start path of the exe application that starts the application
Application.ExecutablePath -- the start path an name of the exe application that stats the application
But to use Application you need to include System.Windows.Forms that is not included for example into console applications.
System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) -- This gets the path from the current assembly "dll,exe,..." Is not affected by application type, path changes,... Always return the directory when the Assemby resides.
Environment.CurrentDirectory -- the current directory. This can be changed for example if you navigate into folders.
You can find more about the different connection string options here
http://www.connectionstrings.com/sql-server-2005
I have spent a whole day googling to work this through and finally have a clue from this
Here is my solution:
1. Use |DataDirectory| in connection string
<add name="NorthwindConnectionString" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDbFilename=|DataDirectory|\Northwind.mdf;User Instance=True" providerName="System.Data.SqlClient" />
2.Set DataDirectory in ClassInitialize
[ClassInitialize()]
public static void MyClassInitialize(TestContext testContext)
{
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
int index = baseDir.IndexOf("TestResults");
string dataDir = baseDir.Substring(0, index) + System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
AppDomain.CurrentDomain.SetData("DataDirectory", dataDir);
}
I'm building a simple Windows Forms App with VS2010 with C#3.0. Also using SQL Express 2008 RC2.
I am able to use: |DataDirectory|MyDb.mdf in the connection string alone without changing anything else. The |DataDirectory| points to the location of my .exe file.
I will think that this would be the first thing all of you would try, so that is why I'm specifying my VS and SQL version. Or maybe it is new to C#3.0.
My complete Connection String:
"Server=.\SQLExpress;AttachDbFilename=|DataDirectory|App_Data\ThumbsUpPlayer.mdf;Database=ThumbsUpPlayer;Trusted_Connection=Yes;"
Note that I have added a "App_Data" folder to my application, because I'm used to the Db in that folder, the folder is not recognised by VS.
I don't have Visual Studio here, but what about:
using System.IO;
using System.Windows.Forms;
string appPath = Path.GetDirectoryName(Application.ExecutablePath);
AttachDBFilme = appPath + "\\MyUnitTestDB.mdf"
I did the following. Hopefully it helps someone.
AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory + "../../App_Data"));
Dynamic Path in SQL Server Connection
SqlConnection con="Server=.\SQLExpress;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Database=MyDatabaseForTesting;Trusted_Connection=Yes;" ;

Categories