Getting current path in Windows form application not working properly - c#

I'm working on an app linked to a local db and I'd like to get the path of db dynamically. I don't know where exactly users will copy this app, so I'd like to get the path to the db automatically. I wrote the following code, it gets the path, but not exactly. I mean, if I have my app in: C:\Users\ROG\Desktop , it says that there is no db in C:\Users\ROG . So it doesn't get the last location of it. Why is that and how to solve it?
I connect to it as follow:
var connString = (#"Data Source=" +
Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName +
#"\Angajati.sdf");

Consider using the following code to determine appllication base directory:
AppDomain.CurrentDomain.BaseDirectory
Full code will look like the following:
var connString = "Data Source=" +
System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Angajati.sdf");

try to use the following code
var connString = (#"Data Source=" +
System.IO.Path.Combine(System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().Location),
"Angajati.sdf"));

Rather than using get current directory I suggest using Application Path. That's because if an OpenFileDialog be used the current directory changes but the applicationPath is the same.
System.Reflection.Assembly.GetExecutingAssembly().Location
I hope it would be helpful.

Related

An OLE DB Provider was not specified in the ConnectionString. 'Provider=SQLOLEDB

I am creating an application which uses access file from shared network.The application works fine when the access file is placed local.But when I placed it in shared path and trying to connect.It is throwing an exception."An OLE DB Provider was not specified in the ConnectionString. 'Provider=SQLOLEDB
Here is my code:
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\server\\MyFirstProject\\SampleDB2.accdb";
using (OleDbConnection con = new OleDbConnection(connectionString))
{
string command = "INSERT INTO emp_status(emp_id,hours,feeded_on,comments)";
command += "VALUES(#emp_id,#hours,#feeded_on,#comments)";
Could anyone help me how to resolve this issue and Am I missing something?
I am using OLEB as a datasourse and Access 2013
Any Suggestions or explanations would definitely helps me.
Thanks in advance!!
You need to escape the leading double slash as well...
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\\\server\\MyFirstProject\\SampleDB2.accdb";
I haven't got anything to check this on here, but I'm fairly sure this is your answer. Also, watch out for reserved words, E.g. "hours" might be one in which case it should be [hours].
Also, you haven't specifically included adding the parameter values in your question. I assume you are doing it but if not then see my coding example here...
VB 2010 error (INSERT INTO) syntax error

Copy LocalDB in Winform gives me a 'File being used by another process'

I'm developing a Windows Forms App with VS2012. The data is stored in a SQL Server LocalDB. I'm also using EF6.
At some point I want to zip and send the .mdf file to a server for backup.
The problem is I'm getting the following error 'The process cannot access the file '[filepath]' because it is being used by another process'.
Now I understand that it's my app that is locking the file, but is there any way to unlock it? Or maybe kill the sqlserver client engine?
I'm even considering backing up the localDB File. Is this possible in a winform app?
I can't test it now, but I suggest to execute a standard T-SQL BACKUP command, then take the BAK file, zip it and store/send it.
string backupDB = #"FullPathToYourBackupFile.bak";
string databaseName = "YourDBName"; // This is not the MDF file, but the logical database name
using (var db = new DbContext())
{
var cmd = string.Format("BACKUP DATABASE {0} TO DISK='{1}' WITH FORMAT;",
databaseName, backupDB);
db.Database.ExecuteSqlCommand(cmd, null);
}
Thanks to you all I got this working.
I used Steve's answer but with some modifications.
string backupDB = String.Format(#"{0}\{1}", Constants.Paths.CompressedProjects, Constants.DataBase.FileNameBackup);
string databaseName = Constants.DataBase.LogicalName; // This is not the MDF file, but the logical database name
using (var db = new DBContext())
{
string[] parms = new string[2];
parms[0] = databaseName;
parms[1] = backupDB;
var cmd = "BACKUP DATABASE " + databaseName + " TO DISK='" + backupDB + "' WITH FORMAT;";
db.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, cmd, parms);
}
params in ExecuteSqlCommand cannot be null and I had to add a TransactionalBehavior.DoNotEnsureTransaction because I was getting this error
Cannot perform a backup or restore operation within a transaction
Uploading the LocalDB is now working.
Thank you so much for your help.
Hugo MaurĂ­cio
just found out a new solution
System.Data.SqlClient.SqlConnection.ClearAllPools()
I tested it and it works
Hugo

Database connection from WPF

I have a folder 'Data' in my WPF application in which there is an .sdf database file.
This file is the database for my application.
When developing my app I used a fixed path to my db like this:
'Data Source=P:\Dropbox\Projects\MembersApp\MembersApp\bin\Debug\Data\RF_db.sdf'
Now I want to use the |DataDirectory| value so that the app always can find the db, were ever the app is installed. I found this solution on StackOverflow:
string executable = System.Reflection.Assembly.GetExecutingAssembly().Location;
string path = (System.IO.Path.GetDirectoryName(executable));
AppDomain.CurrentDomain.SetData("DataDirectory", path);
string dataSourceHome = "Data Source=|DataDirectory|\RF_db.sdf";
But is giving me an error on the last line 'Bad compile constant value'. I've tried with:
string dataSourceHome = #"Data Source=|DataDirectory|\RF_db.sdf";
But that doesn't work.
Any idea what's wrong here?
Do not change DataDirectory in your code; it is set by the installer and changing it will prevent your app from knowing where the data was installed. Just use:
string dataSourceHome = #"Data Source=|DataDirectory|\RF_db.sdf";
And nothing else. Do not call AppDomain.CurrentDomain.SetData("DataDirectory", path); that's what is breaking things.
You could use:
string dataSourceHome = string.Format("Data Source={0}\\RF_db.sdf", Environment.CurrentDirectory);
or
string dataSourceHome = string.Format("Data Source={0}\\RF_db.sdf", System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
It looks like your creating a ADO.Net connection string. Isn't there just information missing from your dataSourceHome?
Have a look at this post.
Or a different approach to creating the connection might be found on ConnectionStrings.com.

Pointing datasource to correct folder

I have built my application in c# and have an sql compact DB to go along with it. What do I need to change the location to in order for it to point to the same directory as the application.
For example:
Right now my DB is in C\Windows blah blah...
And in my code I make the source point to that...when I build the project my app is in bin\release along with my DB file, but in my code the source is not pointed to this DB file..does anyone know what I need to insert to point it to the correct DB file?
Thanks..
Is it always going to be in the same directory as the application executable? If so, perhaps you can just set the connection string using the path of the current assembly (assuming everything is in the same place):
string curPath = String.Format("{0}\\{1}", System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase), "MyDatabase.sdf");
SqlCeConnection conn = new SqlCeConnection(String.Format("Data Source = {0}; Password ={1}", curPath , ":PASSWORD:");

C# database file directory

I'm using the windows forms aplication with an ms access database. And i would like to know if there is a way to show the directory of the database file (to save data in it)excpet like this:
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=save.mdb";
OleDbConnection empConnection = new OleDbConnection(conString);
string insertStatement = "INSERT INTO zivila "
+ "([naziv],[kalorij],[beljakovin],[oh],[mascob]) "
+ "VALUES (#naziv,#kalorij,#beljakovin,#oh,#mascob)";
or this:
"Data Source=D:\Simonova aktovka na namizju\matura\test5\save.mdb";
couse if i use the first one the aplication undos the changes i've made when i close it(the aplication)
the second one makes me have to change the path everytime i bring the aplication to another computer(cous the direktory is different of coars)
So... is there another way?
Try this:
Data Source=|DataDirectory|\save.mdb

Categories