public void ExecuteSql(SqlConnection connection, string sqlFile)
{
string sql = "";
using (FileStream strm = File.OpenRead(sqlFile))
{
StreamReader reader = new StreamReader(strm);
sql = reader.ReadToEnd();
}
Regex regex = new Regex("^GO", RegexOptions.IgnoreCase | RegexOptions.Multiline);
string[] lines = regex.Split(sql);
SqlTransaction transaction = connection.BeginTransaction();
using (SqlCommand cmd = connection.CreateCommand())
{
cmd.Connection = connection;
cmd.Transaction = transaction;
foreach (string line in lines)
{
if (line.Length > 0)
{
cmd.CommandText = line;
cmd.CommandType = CommandType.Text;
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException)
{
transaction.Rollback();
throw;
}
}
}
}
transaction.Commit();
}