I'm trying to make it so I can use the program where ever I put the folder so it's not just restricted to be in one specific place.
This is the connection string i'm using right now
string constring = "Data Source = (LocalDB)\\MSSQLLocalDB;
AttachDbFilename = C:\\Users\\hannes.corbett\\Desktop\\Barcode Scanning\\Barcode Scanning\\BarcodeDB.mdf;
Integrated Security = True";
This connection string works fine and all but as said above I want it to be environmental to where I put it
You can provide variables to values such as data source, attachDbFilename, etc. Then retrieve values at the loading event. Or use config file to retrieve connection string. As in first solution appear like this
string constring = "Data Source = "+ YourDataSource +"; AttachDbFilename = "+ YourAttachedDBFilePath +"; Integrated Security = True";
If it is possible, then put the needed database into the AppData folder and then use the following in the ConnectionString
Server=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|BarcodeDB.mdf;Database=BarcodeDB;
If not, then the best way to do it to use the option that proposed Promod, but in that case, you have to know the exact place of the database in every single environment, or do the search in every environment to find necessary DB.
If you want to find the path for your project you can use:
string path = System.AppDomain.CurrentDomain.BaseDirectory;
An alternative, if you decide to store the db file in the build folders (next to your executable):
string path = Path.GetDirectoryName(new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath);
Example:
// filename of your Db file
string filename = "BarcodeDB.mdf";
// combine filename and your local path
string dbFilePath = Path.Combine(path, filename);
// use the db filepath in your constring using string interpolation
string constring = $"Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = {dbFilePath}; Integrated Security = True";
So when you move your project or have it on various machines (assuming the db file is present), it should be able to find it.
You should put database file inside folder app (debug or release) and call it by Application.StartupPath
Related
I load data from sdf database in winforms App. I use full path to the database file . Example :
conn = new SqlCeConnection
{
ConnectionString ="Data Source=F:\\My Documents\\Project1\\bin\\Debug\\Database.sdf"
};
I d like use a relative path to the database file. For example. I have sdf file in folder F:\My Documents\Project1\bin\Debug\Data\file.sdf and I want use relative path in connection string.
Any advice ? Thank you.
Relative path:
ConnectionString = "Data Source=|DataDirectory|\Database.sdf";
Modifying DataDirectory as executable's path:
string executable = System.Reflection.Assembly.GetExecutingAssembly().Location;
string path = (System.IO.Path.GetDirectoryName(executable));
AppDomain.CurrentDomain.SetData("DataDirectory", path);
Try this code to the working directory if database file exists like below.
D:\HMProject\DataBase\HMProject.sdf
string Path = Environment.CurrentDirectory;
string[] appPath = Path.Split(new string[] { "bin" }, StringSplitOptions.None);
AppDomain.CurrentDomain.SetData("DataDirectory", appPath[0]);
Connection string for .sdf file
<add name="LocalDB" connectionString="metadata=res://*/Client.HMProject.csdl|res://*/Client.HMProject.ssdl|res://*/Client.HMProject.msl;provider=System.Data.SqlServerCe.4.0;provider connection string="Data Source=|DataDirectory|\Database\HMProjectDB.sdf;Password=HMProject;Persist Security Info=False;"" providerName="System.Data.EntityClient" />
Thanks
ck.Nitin (TinTin)
After several strange errors with relative paths in connectionstring I felt the need to post this here.
When using "|DataDirectory|" or "~" you are not allowed to step up and out using "../" !
Example is using several projects accessing the same localdb file placed in one of the projects.
" ~/../other" and " |DataDirectory|/../other" will fail
Even if it is clearly written at MSDN here the errors it gave where a bit unclear so hard to find and could not find it here at SO.
Relative to what, your application ? If so then you can simply get the applications current Path with :
System.Environment.CurrentDirectory
And append it to the connection string
In your config file give the relative path
ConnectionString = "Data Source=|DataDirectory|\Database.sdf";
Change the DataDirectory to your executable path
string path = AppDomain.CurrentDomain.BaseDirectory;
AppDomain.CurrentDomain.SetData("DataDirectory", path);
If you are using EntityFramework, then you can set the DataDirectory path in your Context class
<?xml version="1.0"?>
<configuration>
<appSettings>
<!--FailIfMissing=false -->
<add key="DbSQLite" value="data source=|DataDirectory|DB.db3;Pooling=true;FailIfMissing=false"/>
</appSettings>
</configuration>
Would you please try with below code block, which is exactly what you're looking for:
SqlConnection conn = new SqlConnection
{
ConnectionString = "Data Source=" + System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\Database.sdf"
};
I did this in the web.config file. I added to Sobhan's answer, thanks btw.
<connectionStrings>
<add name="listdb" connectionString="Data Source=|DataDirectory|\db\listdb.sdf"/>
</connectionStrings>
Where "db" becomes my database directory instead of "App_Data" directory.
And opened normally with:
var db = Database.Open("listdb");
I had the same issue trying to specify the relative file path for a database connected to a Windows Forms application. I was able to resolve the issue by following the directions for adding a data source to Windows Forms from Microsoft (e.g., for connecting an Access database).
By using this method, Visual Studio will set the relative file paths to your database for you instead of trying to set it manually. If your database is external to your application, it will create a copy of the database and add it to your application in the proper location. Although you can manually alter you connection string in App.config and/or Settings.settings or within one of your scripts, I've found this method to be error prone. Instead, I've found it best to follow the Microsoft instructions, in general.
This worked for me:
string Connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
+ HttpContext.Current.Server.MapPath("\\myPath\\myFile.db")
+ ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\"";
I'm querying an XLSX file so don't worry about any of the other stuff in the connection string but the Data Source.
So my answer is:
HttpContext.Current.Server.MapPath("\\myPath\\myFile.db")
Here's my code which is in the beginning of a method for converting .xls file to .csv.
sourceFile="C:\\Users\\myUser\\Desktop\\Folder\\myFile.xls";
string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sourceFile + ";Extended Properties=\"Excel 8.0;HDR=No;IMEX=1\"";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
And it crashes on the last line, throwing this exception: Unexpected error from external database driver (22).
I tried removing the IMEX=1 part, but it still didn't work.
What is the problem?
I also had the same issue but I had to rename the spreadsheet to a shorter name, then it worked.(SQL 2012 Dev)
Strangely enough, I replaced the file in another folder and it worked. I have no idea why this is happening.
Try to use Microsoft.Jet.OLEDB.4.0 provider. Also I would advise you to use OleDbConnectionStringBuilder to build OleDbConnectionString:
var oleConnectionStringBuilder = new OleDbConnectionStringBuilder { Provider = "Microsoft.Jet.OLEDB.4.0" };
oleConnectionStringBuilder.DataSource = sourceFile;
oleConnectionStringBuilder.Add("Extended Properties", "Excel 8.0");
oleConnectionStringBuilder.Add("HDR", "No");
It seems that there is something wrong with the Microsoft Excel Driver. Try to execute the program in another PC to see whether this error happens.
Please take a look at this KB article:
http://www.codeproject.com/KB/database/ReadExcel07.aspx . You can use OleDb to connect the Excel file.
I hope this can help you and feel free to follow up after you have tried.
i have fixed this by uninstalling Microsoft access DB Engine Security update.Also Uninstall Service pack3 Update of access DB engine 2007. Hope this will work...
In my case I renamed excel file's sheet name(it was too long), after that it worked.
I'm using :
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FilePath + ";Extended Properties=\"Excel 12.0 Xml; IMEX=1;Importmixedtypes=text;\"";
I am trying to save my database file to a specific folder. I am using the following code to attempt this:
dpath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
AppDomain.CurrentDomain.SetData("DataDirectory", dpath);
newConnectString = "Data Source=" + dpath + "\\" + filename;
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings[ConnectStringName].ConnectionString = newConnectString;
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings");
When the program runs, the new file is never created in the destination folder. It is still storing it with the executable. Any insight as to what I might be doing wrong?
Your current code only changes your configuration file, you will also need to File.Copy the database file to the required forlder, or use SqlCeEngine.CreateDatabase with the new connection string.
I have added a service based database(.mdf),to my Window form application project.But I
am not able to give the right path of the database. I am giving the path as follows but it
gives an exception that unable to open the connection
connection = new SqlConnection("user id=Sarao-PC\\Sarao;" +
"password=sarao;server=SARAO-PC\\SQLEXPRESS" +
"Trusted_Connection=yes;" +
"database=Database11 " +
"connection timeout=30");
Database11 is a service based database .
What is the right way to give path of a .mdf file
Why don't you copy it from properties of your database?
goto view tab, select server explorer. it opens up on your left, and you should see your database there, then just right click>properties. and there copy the text from the field 'Connection String'.
You should write like below:
Server=.\SQLExpress;AttachDbFilename=c:\mydbfile.mdf;Database=dbname; Trusted_Connection=Yes;
First, you need to build the path to the file.
So how do you package the mdf file ? If you put it in your VS project, then you set Build action to "Content" you'll have the file in the same directory than you exe.
So to build the path it'll be easy:
string mdfPath = Path.Combine(Application.StartupPath, "MyDb.mdf");
Then just create the connection string using this path:
connection = new SqlConnection("user id=Sarao-PC\\Sarao;" +
"password=sarao;" +
"Trusted_Connection=yes;" +
"database=Database11;" +
"AttachDbFilename=" + mdfPath + ";");
Standard Security Connection strings
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
I need to do my code the following task. I wrote some code as below, but I am getting error while setting connection string. Looks like it does not have set property.
Check if App.config is exists in user’s “Application Data” folder.
If does NOT exists then create App.config with ConnectionString
If does exists then check if it was connection string or not, and if missing then add connection string.
string SomeConnectionString ="My Connection String goes here"
//Checking whether App.config file exits in "Application Data" folder or not
String appDataPath = Environment.GetFolderPath
(Environment.SpecialFolder.LocalApplicationData);
if (!File.Exists(appDataPath + "App.config"))
{
appDataPath = Path.Combine(appDataPath , "App.config");
Configuration config = ConfigurationManager.OpenExeConfiguration
(appDataPath );
var setting = config.ConnectionStrings.ConnectionStrings
["MyConnectionString"];
if (setting == null)
{
Configuration Config = ConfigurationManager.OpenExeConfiguration
(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings
["MyConnectionString"].ConnectionString = SomeConnectionString;
//I am getting error on line above. Looks like there is not set
//property on it
Config.Save(ConfigurationSaveMode.Modified,true);
ConfigurationManager.RefreshSection("connectionStrings");
}
}
else
{
//check whether it has Connection string or not
//if not then add connection string
}
The app.config is only that named in your program. During build process the file is renamed to [ApplicationName].exe.config. So name the file like this. But beware! Normally the program directory is not allowed for write access (only to administrators). Settings-API is the better way!!!!
Have you looked at the Settings API? This might be more appropriate for what you are doing.