using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace MongoTest
{
class Program
{
private static readonly string DatabaseName = "";
private static readonly string Username = "";
private static readonly string Password = "";
private static readonly string AuthenticationDatabase = "";
private static readonly string folder = @"";
static void Main(string[] args)
{
try
{
Command.Execute($"mongorestore --nsInclude \"{DatabaseName}.*\" --dir \"{folder}\" --username {Username} --password {Password} --authenticationDatabase {AuthenticationDatabase} --gzip --drop --stopOnError");
}
catch (Exception ex) when (!ex.Message.Contains("Failed"))
{
}
}
}
public static class Command
{
///
/// This function executes CMD command as a separate process.
///
/// Command to execute. Such as calc.exe
/// Standard ouput of the command
/// Thrown when anything is printed to standard error output.
public static string Execute(string commandText)
{
using (Process process = new Process())
{
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/C " + commandText;
process.Start();
string result = "";
string error = "";
using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
{
process.OutputDataReceived += (sender, e) => {
if (e.Data == null)
outputWaitHandle.Set();
else
result += e.Data;
};
process.ErrorDataReceived += (sender, e) =>
{
if (e.Data == null)
errorWaitHandle.Set();
else
error += e.Data;
};
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
outputWaitHandle.WaitOne();
errorWaitHandle.WaitOne();
if (!String.IsNullOrWhiteSpace(error))
throw new Exception(error);
return result;
}
}
}
}
}