2017-02-17 63 views
0

我試圖讓備份和恢復作爲開始我試圖獲得備份數據庫,這樣寫這樣如何指向數據庫C#WPF的LocalDB的相對路徑

try 
{ 
    string cbdfilename = "c:\\Bbcon.bak"; 
    SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\BbCon.mdf;Integrated Security=True;Connect Timeout=30;"); 
    string sql = "Backup database @DBNAME to Disk = @FILENAME with Format"; 
    SqlConnection.ClearAllPools(); 
    SqlCommand cmd = new SqlCommand(sql, con); 
    cmd.Parameters.AddWithValue("@DBNAME", "BbCon"); 
    cmd.Parameters.AddWithValue("@FILENAME", cbdfilename); 
    con.Open(); 
    try 
    { 
     cmd.ExecuteNonQuery(); 
    } 
    catch(Exception ex) 
    { 
     MessageBox.Show("Backup DB failed" + ex.ToString()); 
    } 
    finally 
    { 
     con.Close(); 
     con.Dispose(); 
    } 
} 
catch (SqlException ex) 
{ 
    MessageBox.Show(ex.Message); 
} 
finally 
{ 
    if (con.State == ConnectionState.Open) 
    { 
     con.Close(); 
    } 
} 

一個代碼,但是當我運行這個代碼我得到一個錯誤的數據庫BbCon不存在檢查你的數據庫中,我不知道什麼是肯定的問題,但我想我已經給出錯誤的數據庫路徑我知道路徑OD數據庫中正確很喜歡

C:\Users\Mahdi Rashidi\AppData\Local\Apps\2.0\NOL11TLW.9XG\CZM702AQ.LPP\basu..tion_939730333fb6fcc8_0001.0002_fd707bbb3c97f8d3 

但這個項目是爲一些其他客戶端,所以當我安裝此軟件到其他計算機路徑將改變,所以我會得到一個錯誤,所以我求求大家幫我找到一個更好的解決方案,創建備份programattically

回答

0

我建議你創建一個app.config文件並把備份目標的路徑有

OR

我做了前一段時間什麼(動態加載組件,但這段代碼可以讓ü根據您正在運行的組件來檢索路徑位置),它是這樣的:

(唐忘記將System.Reflection添加到您的使用清單中)

// get the current assembly from cache 
var currentAssembly = Assembly.GetEntryAssembly(); 

// if current assembly is null 
if (currentAssembly == null) 
{ 
    // get the current assembly from stack trace 
    currentAssembly = new StackTrace().GetFrames().Last().GetMethod().Module.Assembly; 
} 

// get the assemblies path (from returned assembly) 
assembliesPath = Path.GetDirectoryName(currentAssembly.Location); 

從這一點來說,現在你可以連接你「數據路徑」,並保存你的數據在那裏。

希望它有幫助。

+0

它幫助,但現在我得到另一個錯誤無法打開備份設備我很抱歉,如果我對你的問題感到惱火你 –

+0

第二個工作fine.error通過改變路徑C:\用戶\公衆 –

+0

這很好,這個網站的目標是互相幫助。發佈完整的代碼進行深入分析,還有另外一個問題:1)你是否試圖在本地機器上運行應用程序? 2)應用程序和數據庫服務器是否在同一臺計算機上運行?謝謝你。 – rmszc81