The following page does what you need, create a new SQL-Server database.
Edited version, original version used localhost
while my revision uses \\SQLEXPRESS
and placed into a class.
using System;
using System.Data.SqlClient;
using System.IO;
using System.Windows.Forms;
namespace CreateDatabase
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void CreateButton_Click(object sender, EventArgs e)
{
var (success, exception) = DataOperations.CreateDatabase();
if (success)
{
MessageBox.Show("Done");
}
else
{
MessageBox.Show($"{exception.Message}");
}
}
}
public class DataOperations
{
public static (bool success, Exception exception) CreateDatabase()
{
var fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Sample.mdf");
var ldfFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Sample.ldf");
string connectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
var commandText = "CREATE DATABASE MyDatabase ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
$"FILENAME = '{fileName}', " +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%)" +
"LOG ON (NAME = MyDatabase_Log, " +
$"FILENAME = '{ldfFileName}', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
using (var cn = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand(commandText, cn))
{
try
{
cn.Open();
cmd.ExecuteNonQuery();
return (true, null);
}
catch (Exception e)
{
return (false, e);
}
}
}
}
}
}