Problem with punctuation and space when running CMD via C#

Asked

Viewed 265 times

0

I have a program in C# that uses a button to execute a command on the CMD. This command is used to take a database on a server and put it on the machine in a path you choose(Mysqldump).

private void button2_Click(object sender, EventArgs e)
{
    string caminhoArq = Directory.GetCurrentDirectory();
    string nomesever = (string)sever.Text;
    string nomeuser = (string)user.Text;
    string senha = (string)pass.Text;
    string NumeroPorta = (string)porta.Text;
    string banco = (string)comboBox1.Text;
    string caminhoDoArquivo = (string)caminho.Text;
    string data = DateTime.Now.ToString("dd-MM-yyyy");

    try  //Faz Backup
    {
        System.Diagnostics.Process.Start("CMD.exe", "/C \"" + caminhoArq + @"\FuncoesMySQL\mysqldump -u" + nomeuser + " -p" + senha + " -h" + nomesever + " -P" + NumeroPorta + " " + banco + " >  " + caminhoDoArquivo + @"\" + banco + data + ".sql");
    }
    catch
    {
        MessageBox.Show("Erro ao Executar o Comando!");
    }
    MessageBox.Show("backup feito");

}

I use some char type variables to straighten the screen parameters and run the CMD. And it works perfectly!! But when the user name you a space, or even the path where the file will be placed has some space or accentuation, it does not execute the command on CMD.

I need to know how to make this command run on CMD correctly, even with these accentuation challenges.

Example of correct command:

System.Diagnostics.Process.Start("CMD.exe", "/C \"D:\FuncoesMySQL\mysqldump -uroot -p1234 -hservidor -P3305 bancoteste >  C:\bancoteste18-02-2019.sql");
  • Put an example of how the call should look, please

  • 1

    In general it is almost always enough to put snippets of code that contain space between quotation marks, to avoid errors. Have you tried this possibility?

  • how would you do it in this command?

1 answer

0

This occurs when there are spaces or special characters because the space creates a separation in the CMD parameters. Ex.:

cmd.exe /C D:\FuncoesMySQL\mysqldump -uroot ...

Is interpreted by being:

  • cmd.exe: Programme to be implemented
  • /C: First parameter
  • D: Funcoesmysql mysqldump: Second parameter
  • -uroot: Third parameter
  • ... and so on

With space (in the example, say the folder is "Mysql Functions"), it considers:

cmd.exe /C D:\Funcoes MySQL\mysqldump -uroot ...

Is interpreted by being:

  • cmd.exe: Programme to be implemented
  • /C: First parameter
  • D: Functions: Second parameter
  • Mysql mysqldump: Second parameter
  • -uroot: Fourth parameter
  • ... and so on

Soon it will not interpret the parameters correctly resulting in error.

To prevent this, just pass the path between double Pas (""), which will be interpreted all content as a single parameter, e.g.:

cmd.exe /C "D:\Funcoes MySQL\mysqldump" -uroot ...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.