[英]C# Visual Studio - Implementing user authentication using text files
使用Visual Studio 2013和控制台應用程序。
我的問題是,我該如何做:我有一個程序。 我希望程序檢查是否有一個名為Usernames.txt的文件,如果有,什么也不做,如果沒有,請創建一個新文件。
現在,當完成后,我希望控制台要求該人輸入用戶名,當該人輸入用戶名時,我希望程序檢查是否文件名為:Usernames.txt包含該人輸入的用戶名,如果是,然后告訴對方:此用戶名已經存在,請選擇一個新用戶名。 如果沒有,則將其添加到文件中,然后繼續要求輸入密碼,依此類推。
這是到目前為止,我不知道下一步該怎么做:
Console.WriteLine("Username: ");
string uCreation = Console.ReadLine();
bool exists = false;
foreach (string lines in File.ReadAllLines("Usernames.txt"))
{
if (lines == uCreation)
{
Console.WriteLine("Username already exists!");
exists = true;
break;
}
}
if (!exists)
{
File.AppendAllText(@"Usernames.txt", uCreation + Environment.NewLine);
}
我在正確的軌道上嗎? 我不知道D =如果有人可以幫忙一些不錯的解決方案! 謝謝!
您應該能夠修改此代碼以適合您的要求。
class Program
{
static void Main(string[] args)
{
try
{
if (File.Exists(@"c:\Usernames.txt"))
{
Console.WriteLine("File already exists.I am doing nothing.Tadaaaaaaaaaa !!!");
return;
}
else
{
string sContinue = "yes";
HashSet<string> sUserNames = new HashSet<string>();
while (sContinue.Equals("yes"))
{
Console.WriteLine("Enter username:");
string sUserName = Console.ReadLine();
if (!sUserNames.Contains(sUserName))
{
sUserNames.Add(sUserName);
using (StreamWriter oWriter = new StreamWriter(@"c:\Usernames.txt", true))
oWriter.WriteLine(sUserName);
Console.WriteLine("Username {0} was added.Enter yes to continue or no to exit", sUserName);
}
else
Console.WriteLine("Username {0} exists.Enter yes to add new username or no to exit", sUserName);
sContinue = Console.ReadLine();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine("Done");
Console.Read();
}
}
這是您的解決方案:
static void Main()
{
string path = @"C:\Usernames.txt";
if (File.Exists(path))
Console.WriteLine("File already exists. Exiting the application...");
else
{
List<string> list = new List<string>();
string IsContinue = "Y";
while (IsContinue.Equals("Y"))
{
Console.WriteLine("Enter the username --");
string userName = Console.ReadLine();
if (!list.Contains(userName))
{
list.Add(userName);
File.AppendAllText(path, userName + Environment.NewLine);
Console.WriteLine("Success...! Continue (Y/N) ?", userName);
IsContinue = Console.ReadLine().ToUpper();
}
else
Console.WriteLine("{0} already exists. Choose a new Username again.\n", userName);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.