Here's I wrote some code to create login on SQL Server.
1- Add references (Microsoft.SqlServer.Smo, Microsoft.SqlServer.SqlEnum and Microsoft.SqlServer.ConnectionInfo) to your project.
2- Call method CreateLogin which takes to some arguments (documented)
How to create SQL Server Login programmatically?
//This code developed by Ramy Mahrous
//ramyamahrous@hotmail.com
//Its contents is provided "as is", without warranty.
//Add reference to Microsoft.SqlServer.Smo, Microsoft.SqlServer.SqlEnum and Microsoft.SqlServer.ConnectionInfo
/// <summary>
/// Creates login on SQL Server.
/// </summary>
/// <param name="username">Username if login type is windows please provide the domian name</param>
/// <param name="password">Username's password</param>
/// <param name="defaultDatabase">User's default database</param>
/// <param name="loginType">Type of login</param>
public void CreateDatabase(string username, string password,
string defaultDatabase, LoginType loginType)
{
Server sqlServerInstance = new Server(
new Microsoft.SqlServer.Management.Common.ServerConnection(
new System.Data.SqlClient.SqlConnection("Data Source=.;Initial Catalog=Master;Integrated Security=True")));// your connection string I place mine for illustration.. DON'T HARDLY WRITE IT, pass it as argument or add it in application configuration.
Login loginObj = new Login(sqlServerInstance, username);
loginObj.DefaultDatabase = defaultDatabase;
loginObj.LoginType = loginType;
loginObj.Enable();
loginObj.Create(password); //set the password
//there're many properties to do some tasks related to Login object...
}
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.