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;
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")
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
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'm using .net4.0 and c# language.
In my code i have a connection string
oleConnection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;
Data Source = " + filepath + ";
Extended Propertie s= \"Excel 12.0;HDR=yes\"";
and it work well. But when i change a connection string like this:
oleConnection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;
Data Source =" + filepath + ";
Extended Properties =\"Excel 12.0;HDR=no\"";
(I change HDR parameter for "no")
I got error: No value given for one or more required parameters.
error from "Microsoft Office Access Database Engine".
If your referencing a column using say [A1] then this will fail. With HDR=No the columns are referenced as F1, F2 etc.
OleDb Connection HDR Default is YES ans there is no option for that.
Check:
Connection strings for Access 2007
Regards
There is no HDR=no....
The default behavioour is no headers. So just leave out the HDR part completely - that will also mean no headers.
More info:
http://msdn.microsoft.com/en-us/library/ms254500.aspx
I'm getting the "generic error occurred on GDI++ wen trying to save images.
What I am missing here?
string appdatapath = AppDomain.CurrentDomain.GetData("DataDirectory").ToString();
if (!Directory.Exists(appdatapath + "/Images")
Directory.CreateDirectory(appdatapath + "/Images", Directory.GetAccessControl(appdatapath));
if (!Directory.Exists(appdatapath + "/Images/XBLContent/"))
Directory.CreateDirectory(appdatapath + "/Images/XBLContent/", Directory.GetAccessControl(appdatapath));
string imagesdir = Path.Combine(appdatapath, "/Images/XBLContent/");
Image image = FeedUtils.RequestImage(String.Format({0}/{1}/image.jpg", url, c.GUID));
image.Save(imagesdir + c.GUID + "sm.jpg");
Check whether your IIS worker process has write permissions to the local file system, and in particular the folder whether you are saving the image.
Also, use Server.MapPath() to get the physical location.
See this blog for a solution.