I wish to run the mongoexport.exe process through my C# code, for which, let's say, the arguments go something as follows:
--query "query_syntax"
The whole of the above text shall be stored in a string variable in the C# code and passed as the required argument.
The issue now is that C# internally stores such strings with the escape character (). The same escape character even gets retained in the command-line, making my final argument look something as follows:
--query \"query_syntax\"
The above escape character is the reason fro the failure of my code and I fail to find any way about it.
public static string dateConverter(DateTime dt)
{
long decimalNumber = (long)(dt.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
return (Convert.ToString(decimalNumber, 16));
}
public static void Main(string[] args)
{
try
{
CultureInfo provider = CultureInfo.InvariantCulture;
string instr;
Console.WriteLine("Enter the start date");
instr = Console.ReadLine();
DateTime.TryParseExact(instr, "yyyy/MM/dd", provider, DateTimeStyles.None, out startDate);
Console.WriteLine("Enter the end date");
instr = Console.ReadLine();
DateTime.TryParseExact(instr, "yyyy/MM/dd", provider, DateTimeStyles.None, out endDate);
queryFilter = "{_id:{$gte: ObjectId('" + dateConverter(startDate) + "0000000000000000'), $lte: ObjectId('" + dateConverter(endDate) + "ffffffffffffffff')}}";
string expstring = " --db yourDatabaseName --collection yourCollectionName --type json --query " + queryFilter + " --out yourFilePath --jsonArray";
Process export = new Process();
export.StartInfo.FileName = ExportEXEPath;
export.StartInfo.Arguments = expstring;
export.Start();
}
catch (Exception ex)
{
Console.WriteLine("[ERROR]: " + ex.Message);
}
}
None of the solutions mentioned on the internet worked well for me, so I came up with an escape plan rather than a solution to the problem. I stored the double-quotes as a character in a variable, and appended it to the string building statement as per needs. My code then looked something as follows:
I guess your question is not clearly specifying the error. I ran your code in Visual Studio and understood the problem.
The issue is
queryFilter
variable contains a lot of spaces. When you specify command line parameter which contains spaces it should be enclosed in double-quotes.But your
expstring
is not putting thisqueryFilter
value inside quotes. That's the reason the characters after quotes are considered as separate switches and command execution is failing.You will have to make small code change to include double quotes:
I ran the code and below was the command line generated. There are no additional slashes in the output.
This should actually resolve your issue.
Check the code at: dotnet fiddle