问题
I am tring to connect to a local database with w winform c# application
when i set my connection string to Data: Source=C:\Users\PACKARD BELL\documents\visual studio 2010\Projects\GestionStock\MyApp\Mydb.sdf
it works fine but when i set it to Data Source=|DataDirectory|\Mydb.sdf
it dosen't work
i tried to print the connection string with the data directory variable in the console and i found that it dosen't change
i want the connection string to change with the location of the application folder
How can i do that? thanks in advance
回答1:
According to MSDN:
|DataDirectory|
: This is the value that is set through theAppDomain.SetData("DataDirectory", objValue)
method. An ASP.NET application resolves |DataDirectory| to the "/app_data" folder.
Essentially, if you use the |DataDirectory|
value, your database must exist inside the App_Data\
directory in your project. You can change the default value, but in practice this only serves to confuse other developers who might be expecting the default behavior.
So, instead of
Source=C:\Users\PACKARD BELL\documents\visual studio 2010/Projects\GestionStock\MyApp\Mydb.sdf
,
it would be
Source=C:\Users\PACKARD BELL\documents\visual studio 2010\Projects\GestionStock\MyApp\App_Data\Mydb.sdf
回答2:
But the sdf file in the folder App_Data
回答3:
Here's a scrap from an article I've wrote:
// What's the name of the file you want to work with
var file_name = "parse_me.txt";
// Let's assume you're working with the file on your desktop
var path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
// This is needed to "paste" the dir and the file name (it'll add the "\" basically).
var file_location = Path.Combine(path,file_name);
// Now you can do:
string[] read_all_lines = System.IO.File.ReadAllLines(file_location);
Assuming you have the file in there, it should work.
来源:https://stackoverflow.com/questions/25964195/why-doesnt-datadirectory-change-on-run-time