创建基于命令(即控制台)的应用程序 [英] Create a Command-based (i.e. console) application
问题描述
应用程序要求输入用户名和密码。该应用程序匹配已保存的登录名中的登录名和密码,以及在名为login.txt的文本文件中给出的密码。如果用户名和密码正确,那么应用程序{做某事......}
我不想用包含,如果我在文本文件中用这种格式写的,用户名:密码,如何替换它而不是包含???
使用(StreamReader sr = File.OpenText( E: \\login.txt))
{
string [] lines = File.ReadAllLines( E:\\login.txt);
{
if (lines.Contains(Username)&& lines.Contains(Password))
{
.......
}
.Contains
不是问题。
这段代码的问题在于你完成它的方式,登录的任何字符串.txt
将匹配为用户名
和密码
。
因此,如果用户名=a
和密码=a
,您可能会接受代码。
为确保您匹配用户名
并匹配密码
,您需要逐行检查
foreach ( string 行中的行<} b $ b // 检查用户名和密码
}
然后在其组件中拆分Line。 />
foreach ( string 行 行){
string [] Parts = Line.Split( ,);
// 检查用户名和密码
}
然后用部件[0]
和密码检查
with用户名
Parts [1]
。
UserFound = False;
foreach ( string 行 行){
string [] Parts = Line.Split( 跨度>);
// 检查用户名和密码
if (用户名==部件[ 0 ]&& Password == Parts [ 1 ]){
UserFound = True;
break ;
}
if (UserFound){
// 做你需要的事情
}
}
class Foo
{
static void Main( string [] args)
{
string text = File.ReadAllText( E:\\login.txt);
string [] temp = text.Trim()。Split(' :');
string username = temp [ 0 ];
string password = temp [ 1 ];
if (用户名==用户名&&密码==密码)
{
// 做东西
}
}
}
the application ask for user name and password. The application matches the login name and password from the already saved login names and their password given in a text file called "login.txt". If the user name and password are correct then the application { do something ....}
I don't want to use contain, If I wrote in the textfile in this format, username:password, how can replace that instead of contain ???
using (StreamReader sr = File.OpenText("E:\\login.txt"))
{
string[] lines = File.ReadAllLines("E:\\login.txt");
{
if (lines.Contains(Username) && lines.Contains(Password))
{
.......
}
.Contains
is not the problem.
The problem of this code is that, the way you have done it, any string that is inlogin.txt
will match as ausername
and as apassword
.
So ifUsername="a"
andPassword="a"
, it will be probably accepted by your code.
To ensure that you match aUsername
and matchingPassword
, you need to check line by line
foreach (string Line in Lines) { // Check Username and password }
then split the Line in its components.
foreach (string Line in Lines) { string[] Parts= Line.Split(","); // Check Username and password }
then checkUsername
withParts[0]
andPassword
withParts[1]
.
UserFound= False; foreach (string Line in Lines) { string[] Parts= Line.Split(","); // Check Username and password if (Username == Parts[0] && Password == Parts[1]) { UserFound= True; break; } if (UserFound) { // do what you need } }
class Foo { static void Main(string[] args) { string text = File.ReadAllText("E:\\login.txt"); string[] temp = text.Trim().Split(':'); string username = temp[0]; string password = temp[1]; if(username == Username && password == Password) { //do stuff } } }
这篇关于创建基于命令(即控制台)的应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!