2012-02-09 69 views
0

從來就得到了以下的ConnectionString:ConnectionString的mdf文件

string connectionstr = "Data Source=.\\SQLEXPRESS;" + "AttachDbFilename=|DataDirectory|\\..\\..\\Datenbank\\FarmersCalc.mdf;" + "Integrated Security=True;" + "User Instance=true;"; 

據我所知,|DataDirectory|/bin/debug - 文件夾。 mdf文件位於文件夾Datenbank中,這肯定在我輸入連接字符串的文件夾中。

看來,因爲..\\將無法​​正常工作。 有沒有人有解決這個問題的辦法?

+0

你看到的確切錯誤是什麼? – 2012-02-09 19:48:32

+0

我相信| DataDirectory |指的是項目文件夾下的「App_Data」文件夾。 – 2012-02-09 19:53:06

+2

請不要用「C#」等標題來標題。這就是標籤的用途。 – 2012-02-09 20:04:02

回答

2

您可以使用下面的代碼來計算目錄。

//these two lines get the executable's directory 
Uri u = new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase); 
DirectoryInfo d = new DirectoryInfo(Path.GetDirectoryName(u.LocalPath)); 

//this goes up two directories and combines that directory with the rest 
//of the path to the file 
string path = Path.Combine(d.Parent.Parent.FullName, @"Datenbank\FarmersCalc.mdf;"); 
Console.WriteLine(path); 
+0

路徑不包含GetDirectoryName的定義... – user896692 2012-02-09 20:06:14

+0

您使用的是什麼版本的csharp?你需要包含'System.IO'和'System.Reflection'命名空間才能工作,顯然。我懷疑這是問題,只是把它放在那裏。 – 2012-02-09 20:36:21