Search code examples
c#sql-serverprocesssqlcmdexit-code

Starting sqlcmd process in C# doesn't work when startet with exited event


Why does this code work?

Process sql = Process.Start("sqlcmd.exe", param);
sql.WaitForExit(21600000);

But when I run this code nothing happens:

        Process sql = new System.Diagnostics.Process();
        sql.EnableRaisingEvents = true;
        sql.Exited += new EventHandler(sql_Exited);
        sql.StartInfo.FileName = @"sqlcmd.exe";
        sql.StartInfo.Arguments = param;
        sql.Start();

        this.Dispatcher.Invoke((Action)(() => { I_loader.Visibility = Visibility.Visible; })); 

Exited Event:

        private void sql_Exited(object sender, System.EventArgs e)
        {
            eventHandled = true;
            this.Dispatcher.Invoke((Action)(() => { I_loader.Visibility = Visibility.Hidden; }));            
        }

Variable param has the following value:

-S .\\SQLEXPRESS -d mydatabase -v db_src = \"c:\\temp\\update.bak\" -i db\\update.sql -o \"C:\\myprogram\\bin\\Debug\\log\\log_update.txt\"

Solution

  • It works now with this code. I can't really tell why or what's the difference though.

       Process sql = new Process();   
    
       sql.StartInfo.CreateNoWindow = true;
       sql.StartInfo.UseShellExecute = true;
       sql.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
       sql.StartInfo.FileName = @"sqlcmd.exe";
       sql.StartInfo.Arguments = param;
    
       sql.EnableRaisingEvents = true;
       sql.Exited += new EventHandler(sql_Exited);
       sql.Start();