title: C# use script to create database
body: <p>I like to use parameter for <code>FILENAME</code> in the code below, instead of N'D:\DBName.mdf' and N'D:\DBName.ldf'.</p>
  
  <p>How can I change it in the <code>.sql</code> file and how to call it from C# with the parameters?
  Thanks.</p>
  
  <p>SQL script:</p>
  
  <pre><code>CREATE DATABASE [DBName] ON  PRIMARY 
  ( NAME = N'DBName', FILENAME = N'D:\DBName.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
   LOG ON 
  ( NAME = N'DBName_log', FILENAME = N'D:\DBName.ldf' , SIZE = 3456KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
  END
  </code></pre>
  
  <p>C# code</p>
  
  <pre><code>string appPathDB = Path.GetDirectoryName(Application.ExecutablePath) + "\\DBName.mdf";
  string appPathLog = Path.GetDirectoryName(Application.ExecutablePath) + "\\DBName_log.ldf";
  
  private void CreateDatabase()
  {
     string connection = "Data Source=localhost;Initial Catalog=master;User ID=sa;Password=abcd1234";
     FileInfo file = new FileInfo(Path.GetDirectoryName(Application.ExecutablePath) + "\\DBName.sql");
     string script = file.OpenText().ReadToEnd();
     ExecSql(script, connection, "DBName");
     file.OpenText().Close();
  }
  
  public void ExecSql(string sql, string connectionString, string dataBaseNameToPrepend)
  {
     using (SqlConnection conn = new SqlConnection(connectionString))
     {
        conn.Open();
        Server server = new Server(new ServerConnection(conn));
        server.ConnectionContext.ExecuteNonQuery(sql);
        server.ConnectionContext.Disconnect();
        server.ConnectionContext.ExecuteNonQuery(sql);
        MessageBox.Show("DB Uploaded.");
     }
  }
  </code></pre>