Aldo Huerta
Aldo Huerta

Reputation: 15

How to find/compare a specific line inside a text File? Using C#

I have a program for a little enterprise, that in a Form you may add new users, this new user-names will be added in a text file named: employees.txt like this:

User 1

User 2

User 3

User 4

(Without space between the users)

In a second Form, when you want to close the Application, you need write in a textBox which user want close the app and then compare the textbox string with the names inside employees.txt and if they match, the application will close. How to compare a specific line inside a text File?

Or how I can do that?

Upvotes: 1

Views: 234

Answers (2)

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34180

string[] users = System.IO.File.ReadAllLines("employees.txt");
if(users.Any(u=> u == username)) Application.Exit(); // changed assignment to equality comparison

Upvotes: 2

pm100
pm100

Reputation: 50210

start out by reading the file into an array like this using File.ReadAllLines

see - https://msdn.microsoft.com/en-us/library/s2tte0y1(v=vs.110).aspx

Then use various linq methods (like Any, Where, etc) to search the array

Upvotes: 0

Related Questions