如何使用c#调用SQL Server Express命令行来运行.sql文件

问题描述:

我必须为窗口应用程序进行设置,因此我需要在客户端计算机上创建数据库。所以我决定用一个.sql文件创建它,我将在我的资源文件中添加这个文件。由于有一个选项可以在我的程序第一次运行时执行该文件,这将创建我的数据库。如何使用c#调用SQL Server Express命令行来运行.sql文件

但是正如我的一位朋友建议的那样,.sql文件应该从SQL Server Express的命令行执行。

我已经搜索了很多如何从SQL Server 2008 Express命令行中的c#代码执行.sql文件。

我已经看过这些问题

代码:

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(); 
    } 
} 

错误消息:

找不到文件“C:\用户\基兰\桌面\ rahhu升\ Bookster_28 \ HotelReservationSystem \ HotelReservationSystem \ BIN \调试\ HotelReservationScript.sql”

编辑:

我也试过,但我得到了同样的错误

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

为什么你不能像你提供的链接那样做它? – 2012-02-01 19:15:52

+0

你的意思是这样吗? http://forums.learnsqlserver.com/sqlservertopic53.aspx – 2012-02-01 19:18:37

+0

再看看你的错误信息。该文件不存在或无法找到。如果您确定它存在,请检查您的程序是否有权在该文件夹中找到它。这不是一个c#或sql问题 – deltree 2012-02-02 15:09:23

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

错误解决,因为我必须设置该属性的.sql文件复制属性窗口中的每个timr。