SQL Express connection string: mdf file location relative to application location - c#

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;" ;

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";

Connection string to access database in Program files

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.

|DataDirectory| in Project properties > Settings

The connection string setting is below:
Name:
dbPersonConnectionString
Type:
Connection string
Scope:
Application
Value:
Data Source=|DataDirectory|\dbPerson.sdf
When I install & run the application, it looks for DB in C:\MyApp\Data\ folder. It should be C:\MyApp without additional \Data folder.
Should I simply create Data folder in my project and move DB files under that folder or I simply adjust |DataDirectory| -and how-?
EDIT:
string executable = System.Reflection.Assembly.GetExecutingAssembly().Location;
string path = (System.IO.Path.GetDirectoryName(executable));
AppDomain.CurrentDomain.SetData("DataDirectory",path);
This has been asked before. This MSDN post gives a good overview.
It should indeed default to your binaries folder, you can change it with AppDomain.SetData() . If you change it, better do it early.
AppDomain.CurrentDomain.SetData("DataDirectory", Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
This should work always because Directory.GetCurrentDirectory() may return other directory than the executable one
This one solved my problem
AppDomain.CurrentDomain.SetData("DataDirectory", Directory.GetCurrentDirectory());

Where to store connection string for class library in desktop application? Can I use in app.config?

I am new to desktop application development and currently building a desktop application using layered architecture (user interface, DAL, BLL).
In web development I used to store the connection string in web.config and my class library was accessing it from there. Please guide me how & where connection string should be stored for DAL in desktop application. I tried to add an app.config file in my class library and access the connection string like this:
ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString)
But it throuws an error: "Object reference not set to an instance of an object."
Kindly guide me on this. Thanks for your support and sharing.
It should be stored in the app.config of the Windows Application and not the class library. Basically when you run your executable there should be a file called Foo.exe.config (where Foo.exe is the resulting executable of your Windows Application) in the same folder which contains the settings.
So in Visual Studio simply add an app.config file to the WinForms application project and store the settings there. In this case they will be successfully read by your custom library. There's no need to add an app.config file to your class library project as it will never be used.
Yes, in a desktop application, all configuration should be in the app.config for that application. The class libraries used by this desktop application will get their config from that app.config by default.
If this line throws an exception:
ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString
then it's most likely because no <connectionStrings> entry of name "connectionstring" exists. Check for NULL:
if(ConfigurationManager.ConnectionStrings["connectionstring"] != null)
{
string connStr = ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString;
}
It will be stored in app.config file and you can access the connection string as you do in web application:
if(ConfigurationManager.ConnectionStrings["connectionstringName"] != null)
{
string connectionString = ConfigurationManager.ConnectionStrings["connectionstringName"].ConnectionString;
}
Any configuration settings for an application whether app settings or connection strings should be placed in the application's app.config file. In case of your desktop application you can add an "Application Configuration" file or "app.config" and place your connection string in there. Any dependency for that application .. e.g. a class library like a DAL will pull the value it needs for its connection string from the application's *.config file.
You can use app.config or other way you can use simple text file mentioning with connection string in it.
//// Read connection string from the text file
StreamReader sr = new StreamReader(System.Windows.Forms.Application.StartupPath #"C:\ConnectionString.txt");
connStr = sr.ReadLine();

Categories