2015-10-16 48 views
0

我正在製作一個c#控制檯應用程序,並且想添加一個登錄系統。如何將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; 
     } 

我想,使其允許多個用戶名和密碼就可以進入,將工作。

到目前爲止,它只是接受用戶名和密碼'測試',但我想鏈接到另一個文件充滿用戶名和密碼,我可以使用,而不是'測試'。

任何幫助你可以給我或提供的是有用的謝謝!

+0

無論如何,如果我可以輸入多個用戶名和特定於不同配置文件的密碼,那麼這對我很有用。 – Drips

+0

你會因爲使用'goto'而被釘十字架。 –

+0

我還能使用什麼?大聲笑 – Drips

回答

2

你必須做這件事的方法有兩種:

1: Database to store username and password 
2: Save the username and password in file in a uniform format(like comma,tab separated) 

1:數據庫

->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; } 
} 

在此我添加了一個簡單的代碼來讀取空格分隔的密碼文件,並根據您的要求使用它。爲了更安全的方式,你可以引用該文件。謝謝

+0

我可以用什麼來創建數據庫?我怎樣才能將控制檯連接到數據庫? – Drips

+0

你想使用哪個數據庫? –

+0

@soumyasambitKunda我可以使用的任何東西都可以使用,我有什麼選擇? – Drips

相關問題