2012-11-14 16 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非常好!谢谢。 –

相关问题