Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
778 views
in Technique[技术] by (71.8m points)

c# - Connection string with relative path to the database file

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 DocumentsProject1inDebugDatafile.sdf and I want use relative path in connection string. Any advice ? Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...