Search code examples
c#command-promptsqlcmd

Command prompt cannot find file specified


I'm trying to create a utility to auto restore lots of databases but I'm stuck. It's either the path of SQLCMD or the command string is wrong. The Win32Exception was unhandled

An unhandled exception of type 'System.ComponentModel.Win32Exception' occurred in System.dll

Additional information: The system cannot find the file specified

The string is working on command prompt but not on my application. On the command prompt

SQLCMD -E -S Ge\sqlexpress -Q "RESTORE DATABASE dbName FROM DISK='C:\app\dbName_300915_000.bak'"

On my application

@"SQLCMD -E -S Ge\sqlexpress -Q ""RESTORE DATABASE dnName FROM DISK='C:\app\dbName_300915_000.bak'"""

I replaced the SQLCMD with the full path

@"C:\Program Files\Microsoft SQL Server\100\Tools\Binn\SQLCMD.EXE -E -S Ge\sqlexpress -Q ""RESTORE DATABASE dbName FROM DISK='C:\app\dnName_300915_000.bak'"""

still not working. Could it be multiple SQLCMD ??

The code for my app is

ProcessStartInfo psi = new ProcessStartInfo(@"SQLCMD -E -S Ge\sqlexpress -Q ""RESTORE DATABASE dnName FROM DISK='C:\app\dbName_300915_000.bak'""");
        psi.UseShellExecute = false;
        psi.RedirectStandardOutput = true;
        psi.CreateNoWindow = true;
        var proc = Process.Start(psi);

        string s = proc.StandardOutput.ReadToEnd();

        textBox2.Text = s;

Solution

  • For some reason this code

    using System.Diagnostics;
    Process cmd = new Process();
    cmd.StartInfo.FileName = "cmd.exe";
    cmd.StartInfo.RedirectStandardInput = true;
    cmd.StartInfo.RedirectStandardOutput = true;
    cmd.StartInfo.CreateNoWindow = true;
    cmd.StartInfo.UseShellExecute = false;
    cmd.Start();
    cmd.StandardInput.WriteLine("echo Oscar");
    cmd.StandardInput.Flush();
    cmd.StandardInput.Close();
    cmd.WaitForExit();
    Console.WriteLine(cmd.StandardOutput.ReadToEnd());
    

    Found here https://stackoverflow.com/a/32872174/3424327 works!