2013-08-27 40 views
1

我有一個使用SQL Server Compact .SDF數據庫存儲數據的Winforms應用程序。在調試時,應用程序在Visual Studio中運行良好,但是當我使用我的項目的「發佈」選項並在安裝後運行程序時,我總是收到一條錯誤消息:「無法找到數據庫文件」。在發佈時設置SQL Server Compact數據庫的位置

我設置連接字符串如下

string fileName = System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "Cellar.sdf"); 
connString = string.Format("Data Source={0};", fileName); 

數據庫Cellar.sdf是我的程序文件夾內。

enter image description here

很明顯的是,數據庫路徑是錯誤的,但在那裏我設置,我想用「發佈」功能時安裝我的應用程序的路徑,還是有些辦法找出數據庫文件被複制到哪裏的方法?在桌面應用程序中包含本地數據庫文件的正確方法是什麼?

回答

1

您可以包含DataDirectory宏,並將位置設置爲代碼中的合適位置。

connString = string.Format("Data Source=|DataDirectory|\{0};", fileName); 

    private void Application_Startup(object sender, StartupEventArgs e) 
    { 
     // This is our connection string: Data Source=|DataDirectory|\Chinook40.sdf 
     // Set the data directory to the users %AppData% folder 
     // So the Chinook40.sdf file must be placed in: C:\\Users\\<Username>\\AppData\\Roaming\\ 
     AppDomain.CurrentDomain.SetData("DataDirectory", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)); 
    } 

這將需要您在初始應用程序啓動期間將數據庫文件複製到特定位置(如果它不存在)。

+0

我可以運行一行代碼來檢查它是否已經存在,或以其他方式將其複製到那裏,但是,我該如何複製它?我知道目的地,但我怎麼才能找出它在安裝時的部署位置?如果我可以立即設置該位置,我不需要複製它。很多工作,只要選擇一個位置放置在我的意見中就可以。 –

+0

如果您不需要數據庫來保存應用程序更新,只需使用DataDirectory無代碼 – ErikEJ

+1

我最終這樣做了, 'string fileName = System.IO.Path.Combine(ApplicationDeployment.CurrentDeployment.DataDirectory,「Cellar.sdf」 ); Console.WriteLine(fileName); connString = string.Format(「Data Source = {0};」,fileName);' 雖然我認爲你的解決方案是一種更正確的方法來做到這一點! –

相關問題