How to execute MongoDB commands using C# Console Application?

Nuthan Murarysetty
2 min readAug 30, 2021

--

Requirement: The user wants to run the MongoDB restore command using the C# program.

Referred to a few videos, articles but there is no straight solution to fix my requirement. But got some idea from those sources how we can.

Most of the examples I referred to there are directly running the command(Ex: ipconfig,….) and showing it in the window/console.

But for me, I want to change the path to MongoDB Developer tools bin location to run mongorestore we must reside in this location.

Please find the steps which I followed to achieve,

Step 1: Set my working directory: <To MongoDB Developer Tools>

Ex path: @”C:\Program Files\MongoDB\Tools\100\bin”;

Step 2: Create a new .bat file to restore my MongoDB database into local. Added my mongorestore command inside that file.

Ex command: mongorestore — db=<Your_New_DB_Name> dump\\<Source_DB_Backup_Name>

Step 3: Add <FileName>.bat file during configuration in c# program. This you can find in the below script.

Program.cs

System.Diagnostics.Process mongoRestore = new System.Diagnostics.Process();

mongoRestore.StartInfo.FileName = “restore.bat”;

mongoRestore.StartInfo.CreateNoWindow = true;

mongoRestore.StartInfo.WorkingDirectory = @”C:\Program Files\MongoDB\Tools\100\bin”;

mongoRestore.StartInfo.RedirectStandardOutput = true;

mongoRestore.StartInfo.UseShellExecute = false;

mongoRestore.Start();

Screenshot:

Issue: If u see this error “The system cannot find the file specified” then add a full path or relative path to the FileName property.

This is the initial solution that I tried and it’s worked for me. You can use this and try as much you can and optimize it.

Please share your optimized solution in the comment section this will help me and others who are looking for a solution.

Thanks and keep learning :)

--

--

Nuthan Murarysetty
Nuthan Murarysetty

Written by Nuthan Murarysetty

I love sharing things what I know to others and passionate in photography.

No responses yet