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.
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 create a file folder through the program to hold pdfs that I will later generate. I am doing so in my local and internal server, using the same code to do so:
if (!Directory.Exists(pathName))
Directory.CreateDirectory(pathName);
It works fine if it goes to local, but when I send it to the internal path the
Directory.CreateDirectory(pathNameInternal);
creates a file, not an actual file folder which is causing errors later in the code when it tries to access that named folder.
I have no idea why it is creating a file, anyone have any ideas?
Code from comment:
theOut = #"C:\inetpub\wwwroot\UserDownloads";
Directory.CreateDirectory(theOut + "\\" + DBName);
if (copyInternal == true)
{
theOutInternal = #"\\192.168.2.40\c$\inetpub\wwwroot\UserDownloads";
Directory.CreateDirectory(theOutInternal);
Directory.CreateDirectory(theOutInternal + "\\" + DBName);
}
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 was wondering how I would go about doing this.
Normally I don't worry about this because I just stick the CSV file in the Debug Folder and reference it using:
filePath = Application.StartupPath + "\\blah.csv";
But I want do to this a bit differently now because I want to create a good baseline template project that contains this CSV file whenever I make a new project from the template.
But I still want the file path to be relative, IE) I don't want to have to edit the path to that CSV for each new project that I make.
Does anyone know how to set this up?
If I understand what you are needing you could go about it like this.
string appPath;
appPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
appPath = appPath.Replace("file:\\", "");
appPath = appPath + #"\" + "filename.csv";
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;