2

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?

PitAttack76
  • 2,120
  • 5
  • 31
  • 44
  • I found this solution here [StackOverflow][1] which works for me. Just needed to rename my 'Data' folder to 'App_Data' and use this code: string data = @"Data Source=App_Data\RF_db.sdf"; LocalConnection = new SqlCeConnection(data); This works for me when I run my app localy. However when I deploy my app with clickonce it fails. [1]: http://stackoverflow.com/questions/12932963/how-to-set-a-relative-path-to-a-sql-server-compact-database – PitAttack76 Dec 29 '12 at 22:07

3 Answers3

1

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));
sa_ddam213
  • 42,848
  • 7
  • 101
  • 110
  • If he is using an installer or ClickOnce the data directory may not be the application nor the assembly directory. In fact, from his edit it appears it is not. – Dour High Arch Dec 30 '12 at 02:45
1

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.

Dour High Arch
  • 21,513
  • 29
  • 75
  • 90
0

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.

Community
  • 1
  • 1
Jacco
  • 3,251
  • 1
  • 19
  • 29