Search code examples
c#setup-projectsql-server-2008-express

How to call SQL Server Express command line using c# to run a .sql file


I have to make a setup for window application so I need to create a database on client machine. So I decided that I will create it using a .sql file which I will add in my resource file. As there is a option to execute that file on first run of my program that will create my database.

But as one of my friend suggested, that .sql file should be executed from command line of SQL Server Express.

I have searched a lot for how to execute a .sql file from c# code in SQL Server 2008 Express command line.

I already read these questions

Code:

FileInfo file = new FileInfo(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath),  "HotelReservationScript.sql"));                
StreamReader fileRead = file.OpenText();

string script = fileRead.ReadToEnd();

fileRead.Close();
string strConn = System.Configuration.ConfigurationManager.ConnectionStrings["MasterConnectionString"].ConnectionString;

SqlConnection con = new SqlConnection(strConn);
con.Open();

ExecuteScript(con, script);

protected virtual void ExecuteScript(SqlConnection connection, string script)
{
    string[] commandTextArray = System.Text.RegularExpressions.Regex.Split(script, "\r\n[\t ]*GO");

    SqlCommand _cmd = new SqlCommand(String.Empty, connection);

    foreach (string commandText in commandTextArray)
    {
        if (commandText.Trim() == string.Empty) 
            continue;

        if ((commandText.Length >= 3) && (commandText.Substring(0, 3).ToUpper() == "USE"))
        {
            throw new Exception("Create script contains USE statement. Please provide non database specific create scripts!");
        }

        _cmd.CommandText = commandText;
        _cmd.ExecuteNonQuery();
    }
}

Error message:

Could not find file 'C:\Users\Kiran\Desktop\rahhul\Bookster_28\HotelReservationSystem\HotelReservationSystem\bin\Debug\HotelReservationScript.sql'

EDITED :

I also tried this but I get the same error

FileInfo file = new FileInfo(Path.Combine(Path.GetDirectoryName(Environment.GetCommandLineArgs().ToString()), "HotelReservationScript.sql"));

Solution

  • FileInfo file = new FileInfo(Path.Combine(Path.GetDirectoryName(Environment.GetCommandLineArgs().ToString()), "HotelReservationScript.sql"));
    

    error solved as i have to set the properties of that .sql file copy every timr in property window.