Open Command prompt from C# program and run sqlcmd utility

Hi

This is with respect to this post http://forums.microsoft.com/MSDN/ShowPost.aspx PostID=458786&SiteID=1

My C# program creates db and other db objects. I want to run .sql files from C# program. Basically I can read the files and run the command using sqlcommand. Tjis will take a lot of time if the file is large.

I have decided to run the sqlcmd utility providing the .sql file as an input file. For this I need to launch command window and then run sqlcmd with the required params. For some reason the code below does not execute. (Assume the other variables have been declared)

// create the ProcessStartInfo using "cmd" as the program to be run

// Incidentally, /c tells cmd that we want it to execute the command that follows, and then exit.

ProcessStartInfo info = new ProcessStartInfo("cmd", @"/c sqlcmd -S IMTIAZ\\JUNKYARD -d Solumina -U xxx -P xxx -i C:\TEST\sfcore_ini_lib.sql");

//ProcessStartInfo info = new ProcessStartInfo("cmd", @"/c dir");

// The following commands are needed to redirect the standard output.

//This means that it will be redirected to the Process.StandardOutput StreamReader.

info.RedirectStandardOutput = true;

info.UseShellExecute = false;

// Do not create that ugly black window, please...

info.CreateNoWindow = true;

// Now we create a process, assign its ProcessStartInfo and start it

Process p = new Process();

p.StartInfo = info;

p.Start();

// well, we should check the return value here...

// We can now capture the output into a string...

string res = p.StandardOutput.ReadToEnd();

StreamWriter sw = new StreamWriter("C:\\test\\log.txt", true, Encoding.ASCII);

sw.Write(res);

sw.Close();



Answer this question

Open Command prompt from C# program and run sqlcmd utility

  • PeterTPeterT

    Bit of a late response, but I had the same issue and I think your problem is that SQLCMD.EXE starts as a new process and the command window doesn't receive its output like you would think. I ended up just starting sqlcmd as the process instead of cmd, and bingo! I'm also using a separate thread to capture the standardoutput, not sure if that was necessary or not.
  • Sridhar

    Hi

    No takers on this one.....I need the help on this asap.

    Regards

    Imtiaz


  • Open Command prompt from C# program and run sqlcmd utility