2012-11-14 14 views
11

我正在開發一個應該是可移植的應用程序,我使用的是mongodb。Mongodb在一個可移植的C#應用​​程序

通過便攜式我是指我的應用程序與所有的文件夾:dll文件,EXE文件,蒙戈文件,蒙戈數據庫。然後用這個文件夾我可以在任何機器上運行我的應用程序。

然後我需要知道:

  • 有一些庫,讓我來運行mongod的過程中,當應用程序啓動和結束 過程中的應用程序結束時?

  • 存在一個很好的做法,做那些東西?

建議,歡迎提前致謝。

+0

您可以進一步定義 '便攜'?你有什麼要求? –

+0

@ csharptest.net我用便攜的方式編輯問題 –

回答

9

根據MongoDb的安裝說明,它應該很簡單。

的MongoDB開始作爲控制檯應用程序等待連接,讓您的應用程序啓動時,你應該執行MongoDB hidden。我們總是假設所有的mongodb文件都與您的應用程序文件和數據庫文件位於正確的目錄中)。

當您的應用程序終止時,您應該終止進程。

呦應該設置在這個例子中,正確的路徑:

//starting the mongod server (when app starts) 
ProcessStartInfo start = new ProcessStartInfo();  
start.FileName = dir + @"\mongod.exe"; 
start.WindowStyle = ProcessWindowStyle.Hidden; 

start.Arguments = "--dbpath d:\test\mongodb\data"; 

Process mongod = Process.Start(start); 

//stopping the mongod server (when app is closing) 
mongod.Kill(); 

你可以看到有關mongod的配置和運行的詳細信息here

8

我需要做同樣的事情,我的出發點是薩爾瓦多薩爾皮的回答。但是,我發現了一些需要添加到他的例子中的東西。

首先,你需要UseShellExecute設置爲false,ProcessStartInfo對象。否則,當進程開始詢問用戶是否要運行它時,可能會收到安全警告。我不認爲這是需要的。

其次,你需要殺死進程前致電MongoServer對象關機。我遇到了一個問題,它鎖定了數據庫,並且要求在修復過程之前沒有調用Shutdown方法來修復它。 See Here for details on repairing

我的最終代碼是不同的,但是對於這個例子中我使用薩爾瓦多的碼爲基準,爲參考。

//starting the mongod server (when app starts) 
ProcessStartInfo start = new ProcessStartInfo();  
start.FileName = dir + @"\mongod.exe"; 
start.WindowStyle = ProcessWindowStyle.Hidden; 
// set UseShellExecute to false 
start.UseShellExecute = false; 

//@"" prevents need for backslashes 
start.Arguments = @"--dbpath d:\test\mongodb\data"; 

Process mongod = Process.Start(start); 

// Mongo CSharp Driver Code (see Mongo docs) 
MongoClient client = new MongoClient(); 
MongoServer server = client.GetServer(); 
MongoDatabase database = server.GetDatabase("Database_Name_Here"); 

// Doing awesome stuff here ... 

// Shutdown Server when done. 
server.Shutdown(); 

//stopping the mongod server (when app is closing) 
mongod.Kill(); 
+0

我認爲*你需要C#字符串的雙反斜槓。 –

+0

+1非常好!謝謝。 –

相關問題