I have an application with all the interfaces and functionalities. In the same project I put a simple code running in console to check if the database already created on the machine already exists. If not, it should run the script that creates this. The code is as follows:
public static class Program
{
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern bool FreeConsole();
[STAThread]
public static int Main(string[] args)
{
if (args != null && args.Length > 0)
{
Console.ReadLine();
return 0;
}
else
{
String connString = @"Data Source=.\sqlexpress;Initial Catalog=master;Integrated Security=True";
String cmdText = "select * from master.dbo.sysdatabases where name= 'db_teste'";
Boolean bRet;
SqlConnection sqlConnection = new SqlConnection(connString);
SqlCommand sqlCmd = new SqlCommand(cmdText, sqlConnection);
try
{
sqlConnection.Open();
SqlDataReader reader = sqlCmd.ExecuteReader();
bRet = reader.HasRows;
sqlConnection.Close();
}
catch (Exception e)
{
bRet = false;
sqlConnection.Close();
Console.Write(e.Message);
}
if (bRet == true)
{
Console.WriteLine("Atualizando Tabelas...");
}
else
{
string sqlConnectionString = "Data Source=(local);Initial Catalog=master;Integrated Security=True";
var file = new FileInfo(@"C://script.sql");
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);
}
FreeConsole();
var app = new App();
return app.Run();
}
}
This is always the first part to be executed by the program when it runs. Well, I create installers with Visual Studio Installer - > setup wizard.
How to access the SQL script?
var file = new FileInfo(@"C://script.sql");
In this section FileInfo
will search for reference what is already setado , but if during installation the user chooses another location to install the application the application will not be able to find the .sql
file. How can I fix this?
Errorwhileexecuting: