0

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);
        }
    }
  • Code sample please – Lana Mar 29 '19 at 10:24
  • Just added it for your convenience @Lana – Darsh Khetan Mar 29 '19 at 10:33
  • 1
    I see no any escaped double quotes in your argument string. – Lana Mar 29 '19 at 10:45
  • @Lana if you debug the code using suitable breakpoints, you shall see that the argument being passed to command-prompt is something as follows: **--db myDatabase--collection myCollection --type json --query \"{_id:{$gte: ObjectId('5c9d60000000000000000000'), $lte: ObjectId('5c9eb180ffffffffffffffff')}}\" --out myFile.json --jsonArray** – Darsh Khetan Mar 29 '19 at 11:02
  • In watch it will show backslash, but actually when you emit it console. or file, there will be no backslashes. – Manoj Choudhari Mar 29 '19 at 12:27

2 Answers2

2

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 this queryFilter 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:

var expstring = " --db yourDatabaseName --collection yourCollectionName --type json --query \"" 
           + queryFilter 
           + "\" --out yourFilePath --jsonArray";

I ran the code and below was the command line generated. There are no additional slashes in the output.

--db yourDatabaseName --collection yourCollectionName --type json --query "{_id:{$gte: ObjectId('5a497a000000000000000000'), $lte: ObjectId('5c54dd80ffffffffffffffff')}}" --out yourFilePath --jsonArray

This should actually resolve your issue.

Check the code at: dotnet fiddle

Manoj Choudhari
  • 5,277
  • 2
  • 26
  • 37
  • The change in the code that you mentioned above was my very first attempt at resolving the issue, but it does not solve my problem on the whole. The string gets stored correctly syntactically in C# using this method, but the backslashes are included in the command-prompt too as part of the arguments, which causes the whole error. I realized about this while debugging the code that my command-line parameters are indeed being received into the command-prompt with the escape backslash. – Darsh Khetan Mar 29 '19 at 11:00
0

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:

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;

        char ch = '"'; //added statement

        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')}}";

        //reframed statement
        string expstring = " --db yourDatabaseName --collection yourCollectionName --type json --query " + ch + queryFilter + ch + " --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);
    }
}