-2

Struggling to get a command to run under .NET core but no luck.

I have a basic command like below I would like to execute:

mysqldump -h ... -u ... -p... -P 3306 name > backup_020423_153050.sql

I have written a C# class to do this for me:

public static void RunShellCommand(string command, string arguments)
{
    var process = new Process
    {
        StartInfo = new ProcessStartInfo
        {
            FileName = command,
            Arguments = arguments,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
        },
    };
    
    process.Start();
    process.WaitForExit();

    var output = process.StandardOutput.ReadToEnd();
    var error = process.StandardError.ReadToEnd();

    if (!string.IsNullOrEmpty(output))
    {
        Console.WriteLine(output);
    }

    if (!string.IsNullOrEmpty(error))
    {
        Console.WriteLine(error);
    }
}

Calling it like so:

TerminalUtilities.RunShellCommand(command, $"-h {host} -u {username} -p{password} -P {port} {databaseName} > {fileName}");

Although I get

mysqldump: Couldn't find table: ">"

What is going on here? My guess is C# is doing something weird with the input.

nyxusaha
  • 49
  • 6

1 Answers1

0

You passed a > {fileName} part as argument, so the mysqldump try to parse these arguments and to threat > symbol as a table name.

I suppose you want to redirect mysqldump output into the file. In this case you should not pass > {fileName} as arguments but should configure standard output redirect instead. You can use Process.RedirectStandardOutput for this. See here for sample code Redirect process output C# or here redirecting output to the text file c# (note the answer which uses cmd and its capabilities to perform redirection. Not best, but interest way.)

Serg
  • 3,454
  • 2
  • 13
  • 17
  • I think this is more of a comment than an answer, but nonetheless standard output is enabled. Disabling it also causes the same issue – nyxusaha Apr 02 '23 at 15:10
  • 1
    You need not only set `Redirect...` flag to true, you also need to remove the redirection part from passed arguments string and implement manual capturing of the output and saving it into the file (instead of writing into console as it is done in your code). Please refer linked answers for implementation examples. – Serg Apr 02 '23 at 15:30