Is there an existing method in C# to extract the file path from a string that represents a ConnectionString to a SqlCE .sdf file? I want to check if the file exists at initialization and back it up if the file has been modified.
Sample connection string:
strConn = "Data Source=|DataDirectory|\dbAlias.sdf";
You can use SqlCeConnectionStringBuilder class to parse existing Sql Compact connection string.
A bit late perhaps, but I came across this question wile struggling with the same problem. You can find the location of the |DataDirectory| folder with AppDomain.CurrentDomain.GetData("DataDirectory"). So your connectionstring can be translated like this:
strConn .Replace("|DataDirectory|", AppDomain.CurrentDomain.GetData("DataDirectory").ToString())
You could just create the connection and get the data source from it as a property:
string data;
using (var conn = new SqlConnection(connectionString)) {
data = conn.DataSource;
}
For LocalDB and SqlConnection (not CE):
public static string GetFilePathFromConnectionString(string connectionString)
{
var attachDbFileName = new SqlConnectionStringBuilder(connectionString).AttachDBFilename;
return attachDbFileName.Replace("|DataDirectory|", AppDomain.CurrentDomain.GetData("DataDirectory").ToString());
}
Related
I was given a method to get our database connection string to Sql Server:
SqlConnection GetConnectionString()
I call that and get what the connection string should be. If the database does not exist, I need the connection string without the database name in it. If I try to use the connection string with the database name in it, I get an error that it cannot connect to the database, which is it since it does not exist.
I am calling like this:
using (var connection = new SqlConnection(GetConnectionString().ConnectionString))
Is there a way to recreate the connection string easily without the database name?
SqlConnectionStringBuilder aBuilder =
new SqlConnectionStringBuilder(yourConnectionStringWithDatabase);
aBuilder.InitialCatalog = "";
string yourConnectionStringWithoutDatabase = aBuilder.ConnectionString;
It's easy
var connectionString = "data source=someInstance;initial catalog =someDatabase;etc.";
var pattern = "initial catalog[=\\s\\w]+;";
var dbRemoved = Regex.Replace(connectionString, pattern, "");
Note that I haven't handled case sensitivity, but this should be a good start for your requirements.
How i get full path of database(.mdb) in c# which is connected by ODBC connection ?
Desire output:-
String path="path of ms access file";
Is there any method or function available in c# to get db location ?
This seems to work for me:
using (OdbcConnection con = new OdbcConnection(myConnectionString))
{
con.Open();
String path = con.Database;
Console.WriteLine(path);
It doesn't just parse the connection string, because when myConnectionString is DSN=db1; (a System DSN), path still contains
C:\Users\Public\Database1.accdb
To get the connection string from my App.config I write this code:
ConnectionStringSettings settings
= ConfigurationManager.ConnectionStrings["livresEntities"];
string connectString = settings.ConnectionString;
Console.WriteLine("Original: "+ connectString);
The result (I use Data Model .edmx file):
Original: metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=MySql.Data.MySqlClient;provider connection string="server=localhost;user id=root;persistsecurityinfo=True;database=livres"
But when I want to change the password or the uid using this line:
MySqlConnectionStringBuilder builder
= new MySqlConnectionStringBuilder(connectString);<br>
It give me the following error:
Keyword not supported
Why? If there is any tutorial on how to secure MySQL's connection string using a Model (.edmx) it will be very helpful for me.
I have this connection string :
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\Release\DB.accdb"); // Database Connection
I want my program to connect to the database without the "..\Release\" in the string.
What I mean is, that i want the program to look for the database in the program's folder, without specifying the folder's name (whatever the folder's name is).
How is that done?
You should add your DB to the project (Add -> Existing Item...) and set Build Action to Content and Copy to Output Directory to Copy always:
After that you can using following connection string:
string cs = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=test.mdb;Persist Security Info=False;";
Following code, will find database file in program folder or sub-folder:
string programPath = System.IO.Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName;
var dbPath = System.IO.Directory.GetFiles(programPath, "*.accdb", SearchOption.AllDirectories).FirstOrDefault();
string cs = null;
if (!string.IsNullOrEmpty(dbPath))
{
cs = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Persist Security Info=False;", dbPath);
}
Perhaps you could use something like
String strAppDir = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
String strFullPathToMyFile = System.IO.Path.Combine(strAppDir, "DB.accdb");
ref:
How to: Get the Application Directory
If I'm letting Visual Studio take care of adding an SQL Server database to an existing project, it adds the connection string to app.config. How can I use use THAT connection string to make my own connections and datasets?
Use the ConfigurationManager.AppSettings to read the connection string when required.
For example, if you opening a SQL Connection, use the assign the "Connection String" property to the value retrieved from ConfigurationManager.AppSettings ("MyConnectionString")
If it is placed in the appropriate section in the app config file, then you can use ConfigurationManager.ConnectionStrings to retrieve it as well.
Read more here http://msdn.microsoft.com/en-us/library/ms254494.aspx
Place the connection string in your app.config then use
ConfigurationManager.ConnectionStrings[str].ConnectionString.ToString();
to get the connection string.
For example:
private string GetConnectionString(string str)
{
//variable to hold our return value
string conn = string.Empty;
//check if a value was provided
if (!string.IsNullOrEmpty(str))
{
//name provided so search for that connection
conn = ConfigurationManager.ConnectionStrings[str].ConnectionString.ToString();
}
else
//name not provided, get the 'default' connection
{
conn = ConfigurationManager.ConnectionStrings[ConnStr].ConnectionString;
}
//return the value
return conn;
}
Then you can reference the connection using ado.net or Linq
For Example:
your app.config would contain an entry like:
<connectionStrings>
<add name="nameofConnString" connectionString="Data Source=SQLDATA;Initial Catalog="nameofdatabase";Persist Security Info=True;User ID=username;Password=password;Connection Timeout=30;Pooling=True; Max Pool Size=200" providerName="System.Data.SqlClient"/>
'
Then you could call
conStr = GetConnectionString("nameofConnString")
With Ado.net
You could then establish the connection with:
sqlConn = new SqlConnection(conStr);
sqlConn.Open();
Or with Linq
LinqData ld = new LinqData();
DataContext dataContext = new DataContext(ld.GetConnectionString(sqlConn));
where LinqData is a class that contains the GetConnectionString() method.
Well, both of those helped get me on the right track. I found this quite simple, yet highly annoying. The solution I used was:
using System.Configuration;
add a reference System.configuration
create a new connection with SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabaseConnectionFromApp.Config"].ConnectionString)