如何将c#控制台连接到数据库
本文关键字:连接 数据库 控制台 | 更新日期: 2023-09-27 18:18:06
我正在制作一个c#控制台应用程序,并想添加一个登录系统。
我已经有了这个代码:
Start:
Console.Clear();
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("Enter Username.");
string strUsername = Console.ReadLine();
string strTUsername = "Test";
if (strUsername == strTUsername)
{
Console.Clear();
Console.WriteLine("Enter Password");
Console.ForegroundColor = ConsoleColor.Gray;
string strPassword = Console.ReadLine();
string strTPassword = "Test";
if ( strPassword == strTPassword)
{
Console.Write("Logging in.");
Thread.Sleep(1000);
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("The password you entered is wrong.");
Thread.Sleep(2000);
goto Start;
}
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("The username you entered is wrong.");
Thread.Sleep(2000);
goto Start;
}
我想让它允许多个用户名和密码,你可以输入,将工作。
到目前为止,它只接受用户名和密码'Test',但我想把它链接到另一个充满用户名和密码的文件,我可以使用而不仅仅是'Test'。
你能给我的任何帮助或提供是有用的,谢谢!
有两种方法:
1: Database to store username and password
2: Save the username and password in file in a uniform format(like comma,tab separated)
<<p> 1:数据库/strong> ->Select a database to use
->create a table with columns such as username and password
->connect to database from your app
->get username from console and compare it with the rows of database and check if the password given is correct.
2:文件
->Save a file with username and password with a certain format(comma,space or tab separated)
->Import those from the file to a Dictionay<users>.
->compare the entered password and user name with the dictionary items.
你可以使用加密使文件或数据库更安全。
static void Main(string[] args)
{
List<User> usersList = new List<User>();
string[] lines = System.IO.File.ReadAllLines("users.txt");
foreach ( var line in lines)
{
User user = new User();
user.user = line.Split(' ')[0];
user.password = line.Split(' ')[1];
usersList.Add(user);
}
foreach (var item in usersList)
{
Console.WriteLine(item.user);
Console.WriteLine(item.password);
}
Console.ReadLine();
}
}
public class User
{
public string user { get; set; }
public string password { get; set; }
}
在此,我添加了一个简单的代码来读取空格分隔的密码文件,并根据您的要求使用它。为了更安全,您可以对文件进行加密。谢谢你