如何循环遍历文件获取数据?
How to loop through a file to get data?
我正在尝试进行基本登录并注册 c# 控制台应用程序,但是,我需要遍历我的文件以查看用户输入的用户名和密码在登录时是否匹配。如果用户键入在用户名和密码中,我希望我的代码通过我的文件来检查它是否是现有的用户名和密码
这是我的代码:
[Serializable]
public class Users
{
public string UserName;
public string Password;
public Users(string userName, string password)
{
UserName = userName;
Password = password;
}
}
public class SaveToFile
{
public static void SerializeSignUpDetails(string userName, string password)
{
Users obj = new Users(userName, password);
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("SignUp.txt", FileMode.Append, FileAccess.Write);
formatter.Serialize(stream, obj);
stream.Close();
}
public static Users DeserializeSignUpDetails()
{
Stream stream = new FileStream("SignUp.txt", FileMode.Open, FileAccess.Read);
IFormatter formatter = new BinaryFormatter();
Users objnew = (Users)formatter.Deserialize(stream);
stream.Close();
return objnew;
}
}
public static void Main(string[] args)
{
Console.WriteLine("To Login Type 1, To Create a new account Type 2");
int LogInOrSignUp;
do
{
int.TryParse(Console.ReadLine(), out LogInOrSignUp);
} while (LogInOrSignUp != 1 && LogInOrSignUp != 2);
string userName = "";
string password = "";
bool successfull = false;
Users userDetails = SaveToFile.DeserializeSignUpDetails();
while (!successfull)
{
if (LogInOrSignUp == 1)
{
Console.WriteLine("Write your username:");
userName = Console.ReadLine();
Console.WriteLine("Enter your password:");
password = Console.ReadLine();
if (userName == userDetails.UserName && password == userDetails.Password)
{
Console.WriteLine("You have logged in successfully!");
successfull = true;
break;
}
if (!successfull)
{
Console.WriteLine("Your username or password is incorect, try again!");
}
}
else if (LogInOrSignUp == 2)
{
Console.WriteLine("Enter a username:");
userName = Console.ReadLine();
Console.WriteLine("Enter a password:");
password = Console.ReadLine();
successfull = true;
SaveToFile.SerializeSignUpDetails(userName, password);
}
}
}
我想使用 foreach 循环遍历我的文件,但我不确定如何。
感谢任何帮助!
因为 OP 在一个文件中提供了有关多个凭据的详细信息。
最常见的方式是序列化。二进制或 xml 都可以。
相关主题:
Saving Data Structures in C#
但是版本兼容可能是您的下一个问题。
Version tolerant serialization 可能会解决您的问题。
======
假设您的文件夹中有一堆 txt。
必须完成两件事。
- 函数接受文件路径参数。
- 帮助您遍历所有文件的函数。
重写 DeserializeSignUpDetails
以采用文件路径。
public static Users DeserializeSignUpDetails( string szPath)
{
Stream stream = new FileStream( szPath, FileMode.Open, FileAccess.Read);
IFormatter formatter = new BinaryFormatter();
Users objnew = (Users)formatter.Deserialize(stream);
stream.Close();
return objnew;
}
遍历文件并获取所有登录凭据。它可以放在你的主程序中。
List<Users> GetAllLoginCredential()
{
List<Users> list = new List<Users>();
string[] files = Paths.GetFileName( "D:\YourDirectory" );
foreach( var path in files ){
Users user = SaveToFile.DeserializeSignUpDetails( path );
list.Add( user );
}
}
然后你可以检查每个用户。您也可能希望缓存它以防止重复打开文件。
顺便说一下,Users
只有一个用户信息,您可能希望它是 User
。
你可能需要看的几个要点 -
- 将 class 名称从
Users
更改为 User
,因为这是 user
. 的单一表示形式
您可以convert
所有存储在文件中的用户List<User>
如下图:
public static List<Users> DeserializeSignUpDetails()
{
List<Users> users = new List<Users>();
using (Stream stream = new FileStream(@"SignUp.txt", FileMode.Open, FileAccess.Read))
{
if (stream.Length != 0)
{
BinaryFormatter formatter = new BinaryFormatter();
while (stream.Position != stream.Length)
{
users.Add((Users)formatter.Deserialize(stream));
}
return users;
}
}
return users;
}
然后您可以在 Main class 中使用它,如下所示:
List<Users> userDetails = SaveToFile.DeserializeSignUpDetails();
AND 在登录验证期间如下所示:
if (userDetails != null)
{
foreach (Users user in userDetails)
{
if (userName == user.UserName && password == user.Password)
{
Console.WriteLine("You have logged in successfully!");
successfull = true;
break;
}
if (!successfull)
{
Console.WriteLine("Your username or password is incorect, try again!");
}
}
}
其他注意事项:
在读取流时使用 using
以正确处理。
在 serialize/de-serialize 之前检查 Null
或 empty
以鼓励 defensive programming
类似 -
的流
if (stream.Length != 0)
要使用序列化为多个条目保留登录记录,您需要序列化对象列表。在您的情况下,您可以创建几个可序列化的 classes,User
class 封装单个条目的数据,以及 Users
class 包含a List<User>
个对象加上数据操作方法。
✔ 注意:名字随意。
◉ 要导入的命名空间
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
◉ 用户 class
[Serializable]
public class User
{
public string UserName { get; set; }
public string Password { get; set; }
//More details...
public User(string userName, string password)
{
UserName = userName;
Password = password;
}
public override string ToString() => $"{UserName}, {Password}";
}
◉ 用户 class
[Serializable]
public class Users
{
public readonly List<User> Accounts;
public Users() => Accounts = new List<User>();
public void Save(string filePath)
{
if (string.IsNullOrEmpty(filePath)) return;
var bf = new BinaryFormatter();
using (var fs = new FileStream(filePath, FileMode.Create))
bf.Serialize(fs, this);
}
public static Users Load(string filePath)
{
if (!File.Exists(filePath)) return null;
var bf = new BinaryFormatter();
using (var sr = new FileStream(filePath, FileMode.Open))
return bf.Deserialize(sr) as Users;
}
public bool ContainsUserName(string userName) =>
Accounts.Any(x => x.UserName == userName);
public bool ContainsAccount(string userName, string pass) =>
Accounts.Any(x => x.UserName == userName && x.Password == pass);
public User Get(string userName, string pass) =>
Accounts.FirstOrDefault(x => x.UserName == userName && x.Password == pass);
public bool Add(string userName, string pass)
{
if (ContainsUserName(userName)) return false;
Accounts.Add(new User(userName, pass));
return true;
}
}
在您的实施中,创建、加载和保存您的数据:
//Load...
users = Users.Load(dataFilePath);
//Or create new object...
if (users is null)
users = new Users();
//and when it comes to save...
users.Save(dataFilePath);
使用ContainsUserName
方法查明给定的用户名是否已经存在,以避免重复。 Add
方法将执行相同的操作,并且会将有效的新条目添加到列表中。 Get
方法在列表中搜索给定的用户名和密码,return 搜索 User
对象,否则 null
,ContainsAccount
方法将执行相同的操作如果你不需要 return 一个 User
对象。
var user = users.Get("user", "pass");
if (user is null)
Console.WriteLine("Incorrect username and/or password...");
//or
if (!users.ContainsAccount("user", "pass"))
Console.WriteLine("Incorrect username and/or password...");
在你的 main
中应用它:
public static void Main(string[] args)
{
Console.WriteLine("To Login Type 1, To Create a new account Type 2");
int LogInOrSignUp;
do
{
int.TryParse(Console.ReadLine(), out LogInOrSignUp);
} while (LogInOrSignUp != 1 && LogInOrSignUp != 2);
var filePath = Path.Combine(AppContext.BaseDirectory, "SignUp.dat");
var userName = "";
var password = "";
var successfull = false;
var userDetails = Users.Load(filePath);
if (userDetails is null)
userDetails = new Users();
while (!successfull)
{
if (LogInOrSignUp == 1)
{
Console.WriteLine("Write your username:");
userName = Console.ReadLine();
Console.WriteLine("Enter your password:");
password = Console.ReadLine();
if (userDetails.ContainsAccount(userName, password))
{
Console.WriteLine("You have logged in successfully!");
successfull = true;
break;
}
else
Console.WriteLine("Your username or password is incorect, try again!");
}
else //if (LogInOrSignUp == 2)
{
Console.WriteLine("Enter a username:");
userName = Console.ReadLine();
if (userDetails.ContainsUserName(userName))
Console.WriteLine("The username is taken. Try another one.");
else
{
Console.WriteLine("Enter a password:");
password = Console.ReadLine();
successfull = true;
userDetails.Add(userName, password);
userDetails.Save(filePath);
Console.WriteLine($"A new account for {userName} has been created.");
}
}
}
Console.ReadLine();
}
✔ 注意: 最好使用 switch 语句来 select LogInOrSignUp
而不是 if
语句
我正在尝试进行基本登录并注册 c# 控制台应用程序,但是,我需要遍历我的文件以查看用户输入的用户名和密码在登录时是否匹配。如果用户键入在用户名和密码中,我希望我的代码通过我的文件来检查它是否是现有的用户名和密码
这是我的代码:
[Serializable]
public class Users
{
public string UserName;
public string Password;
public Users(string userName, string password)
{
UserName = userName;
Password = password;
}
}
public class SaveToFile
{
public static void SerializeSignUpDetails(string userName, string password)
{
Users obj = new Users(userName, password);
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("SignUp.txt", FileMode.Append, FileAccess.Write);
formatter.Serialize(stream, obj);
stream.Close();
}
public static Users DeserializeSignUpDetails()
{
Stream stream = new FileStream("SignUp.txt", FileMode.Open, FileAccess.Read);
IFormatter formatter = new BinaryFormatter();
Users objnew = (Users)formatter.Deserialize(stream);
stream.Close();
return objnew;
}
}
public static void Main(string[] args)
{
Console.WriteLine("To Login Type 1, To Create a new account Type 2");
int LogInOrSignUp;
do
{
int.TryParse(Console.ReadLine(), out LogInOrSignUp);
} while (LogInOrSignUp != 1 && LogInOrSignUp != 2);
string userName = "";
string password = "";
bool successfull = false;
Users userDetails = SaveToFile.DeserializeSignUpDetails();
while (!successfull)
{
if (LogInOrSignUp == 1)
{
Console.WriteLine("Write your username:");
userName = Console.ReadLine();
Console.WriteLine("Enter your password:");
password = Console.ReadLine();
if (userName == userDetails.UserName && password == userDetails.Password)
{
Console.WriteLine("You have logged in successfully!");
successfull = true;
break;
}
if (!successfull)
{
Console.WriteLine("Your username or password is incorect, try again!");
}
}
else if (LogInOrSignUp == 2)
{
Console.WriteLine("Enter a username:");
userName = Console.ReadLine();
Console.WriteLine("Enter a password:");
password = Console.ReadLine();
successfull = true;
SaveToFile.SerializeSignUpDetails(userName, password);
}
}
}
我想使用 foreach 循环遍历我的文件,但我不确定如何。
感谢任何帮助!
因为 OP 在一个文件中提供了有关多个凭据的详细信息。 最常见的方式是序列化。二进制或 xml 都可以。
相关主题: Saving Data Structures in C#
但是版本兼容可能是您的下一个问题。
Version tolerant serialization 可能会解决您的问题。
====== 假设您的文件夹中有一堆 txt。
必须完成两件事。
- 函数接受文件路径参数。
- 帮助您遍历所有文件的函数。
重写 DeserializeSignUpDetails
以采用文件路径。
public static Users DeserializeSignUpDetails( string szPath)
{
Stream stream = new FileStream( szPath, FileMode.Open, FileAccess.Read);
IFormatter formatter = new BinaryFormatter();
Users objnew = (Users)formatter.Deserialize(stream);
stream.Close();
return objnew;
}
遍历文件并获取所有登录凭据。它可以放在你的主程序中。
List<Users> GetAllLoginCredential()
{
List<Users> list = new List<Users>();
string[] files = Paths.GetFileName( "D:\YourDirectory" );
foreach( var path in files ){
Users user = SaveToFile.DeserializeSignUpDetails( path );
list.Add( user );
}
}
然后你可以检查每个用户。您也可能希望缓存它以防止重复打开文件。
顺便说一下,Users
只有一个用户信息,您可能希望它是 User
。
你可能需要看的几个要点 -
- 将 class 名称从
Users
更改为User
,因为这是user
. 的单一表示形式
您可以
convert
所有存储在文件中的用户List<User>
如下图:public static List<Users> DeserializeSignUpDetails() { List<Users> users = new List<Users>(); using (Stream stream = new FileStream(@"SignUp.txt", FileMode.Open, FileAccess.Read)) { if (stream.Length != 0) { BinaryFormatter formatter = new BinaryFormatter(); while (stream.Position != stream.Length) { users.Add((Users)formatter.Deserialize(stream)); } return users; } } return users; }
然后您可以在 Main class 中使用它,如下所示:
List<Users> userDetails = SaveToFile.DeserializeSignUpDetails();
AND 在登录验证期间如下所示:
if (userDetails != null)
{
foreach (Users user in userDetails)
{
if (userName == user.UserName && password == user.Password)
{
Console.WriteLine("You have logged in successfully!");
successfull = true;
break;
}
if (!successfull)
{
Console.WriteLine("Your username or password is incorect, try again!");
}
}
}
其他注意事项:
在读取流时使用
using
以正确处理。在 serialize/de-serialize 之前检查
的流Null
或empty
以鼓励defensive programming
类似 -if (stream.Length != 0)
要使用序列化为多个条目保留登录记录,您需要序列化对象列表。在您的情况下,您可以创建几个可序列化的 classes,User
class 封装单个条目的数据,以及 Users
class 包含a List<User>
个对象加上数据操作方法。
✔ 注意:名字随意。
◉ 要导入的命名空间
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
◉ 用户 class
[Serializable]
public class User
{
public string UserName { get; set; }
public string Password { get; set; }
//More details...
public User(string userName, string password)
{
UserName = userName;
Password = password;
}
public override string ToString() => $"{UserName}, {Password}";
}
◉ 用户 class
[Serializable]
public class Users
{
public readonly List<User> Accounts;
public Users() => Accounts = new List<User>();
public void Save(string filePath)
{
if (string.IsNullOrEmpty(filePath)) return;
var bf = new BinaryFormatter();
using (var fs = new FileStream(filePath, FileMode.Create))
bf.Serialize(fs, this);
}
public static Users Load(string filePath)
{
if (!File.Exists(filePath)) return null;
var bf = new BinaryFormatter();
using (var sr = new FileStream(filePath, FileMode.Open))
return bf.Deserialize(sr) as Users;
}
public bool ContainsUserName(string userName) =>
Accounts.Any(x => x.UserName == userName);
public bool ContainsAccount(string userName, string pass) =>
Accounts.Any(x => x.UserName == userName && x.Password == pass);
public User Get(string userName, string pass) =>
Accounts.FirstOrDefault(x => x.UserName == userName && x.Password == pass);
public bool Add(string userName, string pass)
{
if (ContainsUserName(userName)) return false;
Accounts.Add(new User(userName, pass));
return true;
}
}
在您的实施中,创建、加载和保存您的数据:
//Load...
users = Users.Load(dataFilePath);
//Or create new object...
if (users is null)
users = new Users();
//and when it comes to save...
users.Save(dataFilePath);
使用ContainsUserName
方法查明给定的用户名是否已经存在,以避免重复。 Add
方法将执行相同的操作,并且会将有效的新条目添加到列表中。 Get
方法在列表中搜索给定的用户名和密码,return 搜索 User
对象,否则 null
,ContainsAccount
方法将执行相同的操作如果你不需要 return 一个 User
对象。
var user = users.Get("user", "pass");
if (user is null)
Console.WriteLine("Incorrect username and/or password...");
//or
if (!users.ContainsAccount("user", "pass"))
Console.WriteLine("Incorrect username and/or password...");
在你的 main
中应用它:
public static void Main(string[] args)
{
Console.WriteLine("To Login Type 1, To Create a new account Type 2");
int LogInOrSignUp;
do
{
int.TryParse(Console.ReadLine(), out LogInOrSignUp);
} while (LogInOrSignUp != 1 && LogInOrSignUp != 2);
var filePath = Path.Combine(AppContext.BaseDirectory, "SignUp.dat");
var userName = "";
var password = "";
var successfull = false;
var userDetails = Users.Load(filePath);
if (userDetails is null)
userDetails = new Users();
while (!successfull)
{
if (LogInOrSignUp == 1)
{
Console.WriteLine("Write your username:");
userName = Console.ReadLine();
Console.WriteLine("Enter your password:");
password = Console.ReadLine();
if (userDetails.ContainsAccount(userName, password))
{
Console.WriteLine("You have logged in successfully!");
successfull = true;
break;
}
else
Console.WriteLine("Your username or password is incorect, try again!");
}
else //if (LogInOrSignUp == 2)
{
Console.WriteLine("Enter a username:");
userName = Console.ReadLine();
if (userDetails.ContainsUserName(userName))
Console.WriteLine("The username is taken. Try another one.");
else
{
Console.WriteLine("Enter a password:");
password = Console.ReadLine();
successfull = true;
userDetails.Add(userName, password);
userDetails.Save(filePath);
Console.WriteLine($"A new account for {userName} has been created.");
}
}
}
Console.ReadLine();
}
✔ 注意: 最好使用 switch 语句来 select LogInOrSignUp
而不是 if
语句