How to create a . bat file directly from C#?

Asked

Viewed 1,023 times

3

I am making a program in C# and in it I run a file . bat

Look how I turn the file:

string batDir = string.Format(@"C:\Users\Desktop");
    proc = new Process();
    proc.StartInfo.WorkingDirectory = batDir;
    proc.StartInfo.FileName = "teste4.bat";
    proc.StartInfo.CreateNoWindow = false;
    proc.Start();
    proc.WaitForExit();
    MessageBox.Show("Bat file executed !!");
}
catch (Exception ex)
{
    Console.WriteLine(ex.StackTrace.ToString());
}

But now I need create an archive .bat directly from c#. I wish I could write a command to c# and create a file .bat storing this command.

How can I do that? I know that to create a file .txt We use the function:

StreamWriter EscreverTXT = new StreamWriter(@"Disco:local\nomeTXT.log");
EscreverTXT.WriteLine(stringArmazenandoComando);
EscreverTXT.Close();

Now, how to do this except instead of TXT, write a BAT ?

  • 6

    A .bat is a text equal to .txt, only it has another extension.

  • 2

    thanks! I got it here

1 answer

8


Try this way, you just need to put the extension .bat in the file, set the location where you want to create it and insert the code inside it:

int teste = 1;
StreamWriter EscreverTXT = new StreamWriter(@"C:\Temp\file.bat");
EscreverTXT.WriteLine($@"Código bat aqui 
   {teste} teste feito aqui
   2 teste feito aqui");
EscreverTXT.Close();
  • but when I write the whole code I need it cuts into a certain option "echo off " + textBox1.Text + " -column-statistics=0 -u" + username + " -p" + password + " -h" + systemName + " -P" + port.Text + " + comboBox1.Text + " > " + path + "checkbox.sql" it stops in the "user name"

  • 1

    Thus int teste=1; EscreverTXT.WriteLine($@"Código bat aqui 
 {teste} teste feito aqui
 2 teste feito aqui"); using the @ you can break the lines without having to concatenate line by line, and the $ to concatenate the variables using the keys, I edited the answer for better understanding.

Browser other questions tagged

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