Click here to Skip to main content
15,887,175 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I have a admin account in Windows Forms. I have a code that create a account to the lusrmgr but the problem is when I want to write username before creating a account, I will always have a username called NowyUzytkownik (in polish language it's: NewUser) and I want to make textbox write a username that really works.

What I have tried:

This is parts of my code from Form2.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography;
using System.Runtime.InteropServices;

namespace WindowsFormsApp1
{
    

    public partial class Form2 : Form
    {
        private static string savedUsername = "";
        private static string savedFirstPassword = "";

        public static string AllForm2 = "";
        private string sqlServerName;

        public string UsernameValue { get; private set; }
        public string PasswordValue { get; private set; }

        public string EnteredUsername { get; private set; }

        List<string> users = new List<string>();
        List<string> passwords = new List<string>();

        public string SqlServerName
        {
            get { return sqlServerName; }
            set { sqlServerName = value; }
        }

        public Form2()
        {
            InitializeComponent();
            CenterToScreen(); //wycentrowanie dialogu

            //this.serverText = serverText;

            
        }

        public static string DataFromUsername { get; set; }
        private int failedAttempts=0; // Licznik nieudanych prób
        private bool buttonBlocked = false; // Flaga określająca, czy przycisk jest zablokowany
        string connectionString = $"Server=localhost;Database=master;Integrated Security=True;"; // Zaktualizuj odpowiednio dane połączenia
        private string selectedUsername = "";

        private void Username_TextChanged(object sender, EventArgs e)
        {
            string[] allowedUsers = {
                "Test",
                "Gość",
                "Konto domyślne",
                "WDAGUtilityAccount",

                "Administrator"
            };
            string inputText = Username.Text.Trim();


            if (allowedUsers.Contains(inputText))
            {
                if (inputText == "Administrator")
                {
                    string allText = $"Domenowy i lokalny użytkownik: {inputText}";
                    // Ustaw połączony tekst w TextBoxie AllText
                    AllText2.Text = allText;
                }
                else
                {
                    string allText = $"Lokalny użytkownik: {inputText}";
                    AllText2.Text = allText;
                }
            }
            else
            {
                string allText = $"Nowy użytkownik: {inputText}";
                AllText2.Text = allText;
            }
            selectedUsername = Username.Text;

            savedUsername = Username.Text;

            UsernameValue = Username.Text;

            EnteredUsername = Username.Text;
        }


private void FirstPassword_TextChanged(object sender, EventArgs e)
        {
            // Tutaj możesz zapamiętać wpisane hasło do TextBox
            string enteredPassword = FirstPassword.Text;
            // Możesz to hasło zapisać w zmiennej lub wykonać inne operacje na nim

            savedFirstPassword = FirstPassword.Text;

            PasswordValue = FirstPassword.Text;
        }



private void NextForm3_Click(object sender, EventArgs e)
        {
            string username = Username.Text;

            string password = FirstPassword.Text;
            string enteredPassword = FirstPassword.Text;

            string password1 = FirstPassword.Text;
            string password2 = FirstPassword.Text;

            string[] dozwoloneNazwy = { "Test", "Gość", "Konto Domyślne", "WDAGUtilityAccount" };
            string wpisaneNazwa = Username.Text;
            string sqlServerName = SqlServerName;

            
            bool containsDigit = false;

            foreach (char c in password1)
            {
                if (char.IsDigit(c))
                {
                    containsDigit = true;
                    break;
                }
            }

            // Sprawdź, czy w haśle jest chociaż jeden znak specjalny
            
            bool containsSpecialCharacter = false;
            foreach (char c in password2)
            {
                if (!char.IsLetterOrDigit(c))
                {
                    containsSpecialCharacter = true;
                    break;
                }
            }

            // Sprawdź, czy hasło zawiera co najmniej jedną dużą literę
            string password3 = FirstPassword.Text;
            bool hasUpperCaseLetter = false;
            foreach (char character in password3)
            {
                if (char.IsUpper(character))
                {
                    hasUpperCaseLetter = true;
                    break;
                }
            }

            // Sprawdź, czy hasło zawiera co najmniej jedną dużą literę
            string password4 = FirstPassword.Text;
            bool hasLowerCaseLetter = false;
            foreach (char character in password4)
            {
                if (char.IsLower(character))
                {
                    hasUpperCaseLetter = true;
                    break;
                }
            }



            //.................................................................................



            if (UserNotExistRadioButton.Checked)
            {

                if (password1 == password2 && !string.IsNullOrEmpty(password1) && !string.IsNullOrEmpty(password2))
                {
                    // Użyj funkcji LogonUser lub innej metody do utworzenia nowego użytkownika
                    // Tutaj dodaj kod do utworzenia użytkownika w systemie

                    // Dodaj nowego użytkownika do ListBox

                    ExistUserList.Items.Add(username);

                    // Wyczyść TextBoxy po dodaniu użytkownika



                    //Username.Text = "";
                    //FirstPassword.Text = "";
                    //SecondPassword.Text = "";

                    // Zapisz użytkowników w pliku
                    SaveUsersToFile();
                }
                
            }



            //.................................................................................



            if (Array.Exists(dozwoloneNazwy, nazwa => nazwa == wpisaneNazwa))
            {
                MessageBox.Show("Wybierz przycisk istniejący użytkownik i wybierz nazwę użytkownika z listy", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            else if (UserExistRadioButton.Checked == false && UserNotExistRadioButton.Checked == false)
            {
                MessageBox.Show("Wybierz przycisk nowy użytkownik lub istniejący użytkownik", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            else if (UserExistRadioButton.Checked)
            {
                if (buttonBlocked)
                {
                    MessageBox.Show("Przycisk jest zablokowany. Poczekaj 10 sekund.");
                    return;
                }
                if (ExistUserList.SelectedItem == null)
                {
                    // Wyświetl komunikat
                    MessageBox.Show("Wybierz istniejącą nazwę użytkownika", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return; // Przerwij działanie metody, aby nie kontynuować
                }

                if (buttonBlocked)
                {
                    MessageBox.Show("Przycisk jest zablokowany. Poczekaj lub skontaktuj się z administratorem.");
                    return;
                }

                // Sprawdź, czy użytkownik istnieje w systemie
                bool userExists = CheckIfUserExists(selectedUsername);

                if (userExists)
                {
                    // Użytkownik istnieje w systemie
                    // Teraz sprawdź, czy hasło jest poprawne
                    bool passwordIsCorrect = CheckIfPasswordIsCorrect(selectedUsername, enteredPassword);

                    if (AuthenticateUser(username, password))
                    {
                        // Użytkownik został uwierzytelniony, przejdź do następnego formularza
                        Form3 next3 = new Form3(username, password);
                        next3.Show();
                        this.Close();
                    }
                    else
                    {
                        failedAttempts++;
                        if (failedAttempts >= 3)
                        {
                            BlockButtonForSomeTime();
                        }
                        else
                        {
                            MessageBox.Show("Podałeś złe hasło. Pozostało prób: " + (3 - failedAttempts));
                        }
                    }
                }
                else
                {
                    // Użytkownik nie istnieje w systemie
                    // Dodaj kod obsługujący brak użytkownika
                    MessageBox.Show("Użytkownik nie istnieje.");
                }



                //.................................................................



                // Sprawdź, czy został wybrany element z listy
                if (ExistUserList.SelectedItem != null)
                {
                    string selectedUsername = ExistUserList.SelectedItem.ToString();
                    string connectionString = $"Server={sqlServerName};Database=master;Integrated Security=True;";
                    using (SqlConnection connection = new SqlConnection(connectionString))
                    {
                        try
                        {
                            connection.Open();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Wystąpił błąd: " + ex.Message);
                        }
                        finally
                        {
                            connection.Close();
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Proszę wybrać użytkownika z listy.");
                }
            }
            // Sprawdzamy, czy przycisk radio UserNotExistRadioButton jest zaznaczony
            else if (UserNotExistRadioButton.Checked)
            {
                // Sprawdzamy, czy pole Username nie jest puste
                if (string.IsNullOrEmpty(Username.Text))
                {
                    MessageBox.Show("Musisz wpisać nazwę użytkownika", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }



                else if (Username.Text.Length < 3)
                {
                    MessageBox.Show("Musisz wpisać 3 lub więcej liter w nazwie użytkownika", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else if (FirstPassword.Text != SecondPassword.Text)
                {
                    failedAttempts++;

                    if (failedAttempts >= 3)
                    {
                        NextForm3.Enabled = false;
                        buttonBlocked = true;
                        FirstPassword.Enabled = false;
                        SecondPassword.Enabled = false;
                        FirstPassword.Text = string.Empty;
                        SecondPassword.Text = string.Empty;
                        failedAttempts = 0; // Zerujemy liczbę nieudanych prób
                        MessageBox.Show("Podałeś złe hasło trzy razy. Przycisk zostanie zablokowany na 10 sekund.");
                        Timer timer = new Timer();
                        timer.Interval = 10000; // 10 sekund w milisekundach

                        Czas czas = new Czas();
                        czas.Show();
                        this.Close();

                        timer.Tick += (s, ev) =>
                        {
                            NextForm3.Enabled = true;
                            buttonBlocked = false;
                            FirstPassword.Enabled = true;
                            SecondPassword.Enabled = true;

                            MessageBox.Show("Przycisk został odblokowany.");
                            timer.Stop();
                        };
                        timer.Start();
                    }
                    else
                    {
                        MessageBox.Show("Hasła muszą być takie same. Pozostało prób: " + (3 - failedAttempts));
                    }
                }
                else if (string.IsNullOrEmpty(FirstPassword.Text) && string.IsNullOrEmpty(SecondPassword.Text) && password.Length < 8)
                {
                    MessageBox.Show("Musisz wpisać hasło, powtórzyć hasło, musisz wpisać 8 znaków w haśle", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else if (!containsDigit && !containsSpecialCharacter && !hasUpperCaseLetter && !hasLowerCaseLetter)
                {
                    MessageBox.Show("Musisz wpisać chociażby jedną liczbę w haśle." +
                                    "Musisz wpisać chociażby jeden znak specjalny w haśle" +
                                    "Musisz wpisać chociażby jedną dużą literę w haśle" +
                                    "Musisz wpisać chociażby jedną mniejszą literę w haśle", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    AllForm2 = AllText2.Text;
                    try
                    {
                        using (SqlConnection connection = new SqlConnection(connectionString))
                        {
                            connection.Open();
                            string query = $"SELECT COUNT(*) FROM sys.server_principals WHERE name = @Username";
                            using (SqlCommand command = new SqlCommand(query, connection))
                            {
                                command.Parameters.AddWithValue("@Username", selectedUsername);
                                int count = (int)command.ExecuteScalar();
                                MessageBox.Show("Połączono użytkownika: " + selectedUsername + " z bazą danych");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Błąd połączenia z bazą danych: " + ex.Message, "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    Form3 next3 = new Form3(username, password);
                    next3.Show();
                    this.Close();
                }

                

                if (string.IsNullOrEmpty(enteredPassword))
                {
                    MessageBox.Show("Musisz wpisać hasło", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                
            }
        }




This is all my Form3.cs code:
using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.Management;

namespace WindowsFormsApp1
{
    public partial class Form3 : Form
    {
        private Form2 form2;

        private string usernameFromForm2;
        private string passwordFromForm2;

        private string enteredUsername;
        private string enteredPassword;

        public Form3(string username, string password)
        {
            this.form2 = form2;
            InitializeComponent();
            CenterToScreen(); //wycentrowanie dialogu

            AllText3.Text = Form1.AllForm1 + "\r\n" + Form2.AllForm2;

            usernameFromForm2 = username;
            passwordFromForm2 = password;

            enteredUsername = username;
            enteredPassword = password;
        }

        private void Back_Click(object sender, EventArgs e)
        {
            Form2 back2 = new Form2();
            back2.Show();
            this.Close();
        }

        private void AllText3_TextChanged(object sender, EventArgs e)
        {
            
        }

        private void NextForm4_Click(object sender, EventArgs e)
        {
            Form2 form2 = new Form2();


            string username = "NowyUzytkownik";
            string password = "NoweHaslo";

            // Tworzenie procesu, aby uruchomić polecenie net user
            Process process = new Process();
            process.StartInfo.FileName = "net";
            process.StartInfo.Arguments = $"user {username} {password} /add";
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.CreateNoWindow = true;

            process.Start();
            string output = process.StandardOutput.ReadToEnd();
            process.WaitForExit();

            if (process.ExitCode == 0)
            {
                MessageBox.Show($"Utworzono nowego użytkownika: {username}");
            }
            else
            {
                MessageBox.Show($"Błąd podczas tworzenia użytkownika. Wynik: {output}");
            }


        }

        private void CreateLocalUserAccount(string username, string password)
        {
            try
            {
                ObjectGetOptions options = new ObjectGetOptions();
                ManagementPath path = new ManagementPath("Win32_UserAccount");
                ManagementClass processClass = new ManagementClass(new ManagementScope("\\\\.\\root\\cimv2"), path, options);

                ManagementBaseObject inParams = processClass.GetMethodParameters("Create");
                inParams["Name"] = username;
                inParams["Password"] = password;
                inParams["Description"] = "Nowy użytkownik";
                inParams["PasswordChangeable"] = true;
                inParams["PasswordExpires"] = false;

                ManagementBaseObject outParams = processClass.InvokeMethod("Create", inParams, null);

                uint result = (uint)(outParams.Properties["ReturnValue"].Value);
                if (result == 0)
                {
                    MessageBox.Show("Utworzono nowego użytkownika: " + username);
                }
                else
                {
                    MessageBox.Show("Błąd podczas tworzenia użytkownika. Kod błędu: " + result);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Wystąpił błąd: " + ex.Message);
            }
        }

    }
}
Posted
Updated 14-Nov-23 2:09am
v2
Comments
Dave Kreskowiak 14-Nov-23 11:32am    
Are you trying to create accounts in the Windows account database? Unless your code is running under a Windows administrator user account already, you can't. Only admin accounts can create other user accounts in Windows.

So, if you have some plain old user that runs this code and tries to create a new account, that operation will fail.

Ummm... I can tell you're copying and posting code from the web and praying that it works. The resulting code you cobbled together is extremely bad. Not only that, but you're also not listening to the advice and code snippets you've already been given on this massive problem of problems.
Maciej Los 14-Nov-23 15:57pm    
Seems that no one can understand what you want to achieve... Please, describe your issue in native language, then use google translator. After that, use "Improve question" and paste that translation.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900