I have an existing .txt file that I would like to use to store my data, but when using this code I get an error at line 39 at switch case 1.
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
public static List<Pw> Site = new List<Pw>();
static void Main(string[] args)
{
string file = #"C: \Users\james\Documents\DataFolder\Vault.txt";
string command = "";
while (command != "exit")
{
Console.Clear();
Console.WriteLine("Please enter a command: ");
command = Console.ReadLine().ToLower();
switch (command)
{
case "1":
AddPw();
File.AppendAllLines(file, Pw.Site);
break;
case "2":
if (File.Exists(file))
{
// Read all the content in one string
// and display the string
string str = File.ReadAllText(file);
Console.WriteLine(str);
}
break;
}
}
}
private static void AddPw()
{
Pw pw = new Pw();
Console.Write("Enter the Username/Email: ");
pw.Username = Console.ReadLine();
Console.Write("Enter Full Name: ");
pw.FullName = Console.ReadLine();
Console.Write("Enter Phone Number: ");
pw.PhoneNumber = Console.ReadLine();
Console.Write("Enter Your Password: ");
string password = Console.ReadLine();
pw.Password = password;
Site.Add(pw);
}
private static void PrintPw(Pw pw)
{
Console.WriteLine("Username/Email: " + pw.Username);
Console.WriteLine("Full Name: " + pw.FullName);
Console.WriteLine("Phone Number: " + pw.PhoneNumber);
Console.WriteLine("Password: " + pw.Password[0]);
Console.WriteLine("-------------------------------------------");
}
private static void ListPw()
{
if (Site.Count == 0)
{
Console.WriteLine("Your address book is empty. Press any key to continue.");
Console.ReadKey();
return;
}
Console.WriteLine("Here are the current people in your address book:\n");
foreach (var pw in Site)
{
PrintPw(pw);
}
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
}
public class Pw
{
public string Username { get; set; }
public string FullName { get; set; }
public string PhoneNumber { get; set; }
public string Password { get; set; }
}
I have updated your existing function.
using this function you can add and append data in existing file.
private static void AddPw(string filePath)
{
try
{
Pw pw = new Pw();
if (!File.Exists(filePath))
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(filePath))
{
Console.Write("Enter the Username/Email: ");
pw.Username = Console.ReadLine();
sw.WriteLine(pw.Username);
Console.Write("Enter Full Name: ");
pw.FullName = Console.ReadLine();
sw.WriteLine(pw.FullName);
Console.Write("Enter Phone Number: ");
pw.PhoneNumber = Console.ReadLine();
sw.WriteLine(pw.PhoneNumber);
Console.Write("Enter Your Password: ");
pw.Password = Console.ReadLine();
sw.WriteLine(pw.Password);
}
}
else
{
using (StreamWriter sw = File.AppendText(filePath))
{
Console.Write("Enter the Username/Email: ");
pw.Username = Console.ReadLine();
sw.WriteLine(pw.Username);
Console.Write("Enter Full Name: ");
pw.FullName = Console.ReadLine();
sw.WriteLine(pw.FullName);
Console.Write("Enter Phone Number: ");
pw.PhoneNumber = Console.ReadLine();
sw.WriteLine(pw.PhoneNumber);
Console.Write("Enter Your Password: ");
pw.Password = Console.ReadLine();
sw.WriteLine(pw.Password);
}
}
}
catch (Exception ex)
{
}
}
File.AppendAllLines(file, Pw.Site);
In this line, you need to pass an IEnumerable for AppendAllLines to work. You can easily convert Site (which is List<Pw>) to an IEnumerable<string> using the ConvertAll method. Here's one way of achieving this:
Replace that line with this:
File.AppendAllLines(file, Site.ConvertAll<string>(
(p) => string.Format("{0} | {1} | {2} | {3}\n",
p.Username,
p.FullName,
p.PhoneNumber,
p.Password
))
);
This "lambda" basically takes your Pw object and converts it into a string inline.
Related
I'm new to programming, basically, as you will be able to see everything works up until I want to ask if the details are correct, whatever I type in it will always take the details as correct, I want to be able to type yes or no to the confirmation. I would really appreciate someone explain this to me so i can use bools properly
namespace UserFeedBack.cs
{
class MainClass
{
static void Main(string[] args)
{
Console.Write("Enter your name : ");
string Name = Console.ReadLine();
Console.WriteLine("Hey there, " +Name );
Console.ReadLine();
Console.Write("How old are you : ");
string Age = Console.ReadLine();
Console.WriteLine(" Hello " + Name + " you are " + Age + "!");
Console.Write("bank card account number :");
string AccountNumber = Console.ReadLine();
Console.WriteLine("Thank you! to confirm, is your account number : " + AccountNumber);
Console.ReadLine();
bool y = true;
if (y)
{
Console.WriteLine("Thank you, we can confirm your details are correct");
}
else
{
Console.WriteLine("re enter your details : ");
}
Console.ReadLine();
}
}
}
You've declared your bool property bool y = true;, and doing that sets the value of the bool to be always true. what you need to do is evaluate what the user is typing with Console.ReadLine(). If the user type "Yes" then you change the property to true, else you change it to false, like this:
class MainClass
{
static void Main(string[] args)
{
Console.Write("Enter your name : ");
string Name = Console.ReadLine();
Console.WriteLine("Hey there, " +Name );
Console.ReadLine();
Console.Write("How old are you : ");
string Age = Console.ReadLine();
Console.WriteLine(" Hello " + Name + " you are " + Age + "!");
Console.Write("bank card account number :");
string AccountNumber = Console.ReadLine();
Console.WriteLine("Thank you! to confirm, is your account number : " + AccountNumber);
bool confirmed = Console.ReadLine().ToLower() == "yes";
if (confirmed)
{
Console.WriteLine("Thank you, we can confirm your details are correct");
}
else
{
Console.WriteLine("re enter your details : ");
}
Console.ReadLine();
}
}
I have a program that finds words within a text file and print them out. But this is a school assignment, and I need to use a certain degree of object oriented programming, like using different classes and interfaces.
So, the issue I have is that I have two public classes, that when called and adopted in the main class, with the main method, prints out the two string values I want.
The code looks like this
public class GetFilePath
{
public string FilePath;
public GetFilePath(string fn)
{
/// string path = "testfile.txt";
FilePath = fn;
}
public void SetFilename(string NewFilePath)
{
FilePath = NewFilePath;
}
}
public class GetSearchWord
{
public string WordSearch;
public GetSearchWord(string st)
{
WordSearch = st;
}
public void SetSearchTerm(string NewSearchTerm)
{
WordSearch = NewSearchTerm;
}
}
These are implemented into the main function as follows
Console.Write("please enter a file to search for: ");
// Call the constructor that has no parameters.
GetFilePath Filepath1 = new GetFilePath("");
Console.WriteLine(Filepath1.FilePath);
Filepath1.SetFilename("testfile.txt");
Console.WriteLine(Filepath1.FilePath);
// Call the constructor that has one parameter.
Console.Write("please enter a word to search for in the file: ");
GetSearchWord SearchedWord1 = new GetSearchWord("");
Console.WriteLine(SearchedWord1.WordSearch);
SearchedWord1.SetSearchTerm("true");
Console.WriteLine(SearchedWord1.WordSearch);
But I need to connect Filepath1.FilePath and SearchedWord1.WordSearch to the following strings
string FilePath = "";
string WordSearch = "";
As you can see those are null at the moment.
which are the key strings in my search function that actually searches up the lines with the words!
The FilePath and WordSearched strings are used as following
using (StreamReader fs = File.OpenText(FilePath))
{
int count = 0; //counts the number of times wordResponse is found.
int lineNumber = 0;
while (!fs.EndOfStream)
{
string line = fs.ReadLine();
lineNumber++;
int position = line.IndexOf(WordSearch);
if (position != -1)
{
count++;
Console.WriteLine("Match#{0} line {1}: {2}", count, lineNumber, line);
}
}
if (count == 0)
{
Console.WriteLine("your word was not found!");
}
else
{
Console.WriteLine("Your word was found " + count + " times!");
}
Console.WriteLine("Press enter to quit.");
Console.ReadKey();
}
what I have tried doing is setting
string WordSearch = SearchedWord1.WordSearch;
as an example of what I am trying to achive since, SearchedWord1.WordSearch is currently set to "true" which is the keyword I want to search my file for.
if I understood your question correctly then the following code should solve your problem(update your main code with the following):
Console.Write("please enter a file to search for: ");
// Call the constructor that has no parameters.
var filePathInput = Console.ReadLine();
GetFilePath Filepath1 = new GetFilePath(filePathInput);
Console.WriteLine(Filepath1.FilePath);
Filepath1.SetFilename("testfile.txt");
Console.WriteLine(Filepath1.FilePath);
// Call the constructor that has one parameter.
Console.Write("please enter a word to search for in the file: ");
var searchWordInput = Console.ReadLine();
GetSearchWord SearchedWord1 = new GetSearchWord(searchWordInput);
Console.WriteLine(SearchedWord1.WordSearch);
SearchedWord1.SetSearchTerm("true");
Console.WriteLine(SearchedWord1.WordSearch);
the change is that this code is getting the input from the user...
Hi I would like to prevent users from entering nothing in the input field.
I've tried using an if else but the console keeps crashing when there's no input. (for both user input and ldap address input ==> I want it to show "No input detected." and allow the user to re-enter the username)
And if I used (results == " "), I would get a error:
"Operator '==' cannot be applied to operands of type
'System.DirectoryServices.SearchResult' and 'string'"
Is there any way for me to resolve this? The codes are as shown below.
Affected codes from line 16 onwards (for the top block of codes)
if (results != null)
{
//Check is account activated
bool isAccountActived = IsActive(results.GetDirectoryEntry());
if (isAccountActived)
Console.WriteLine(targetUserName + "'s account is active.");
else
Console.WriteLine(targetUserName + "'s account is inactive.");
//Check is account expired or locked
bool isAccountLocked = IsAccountLockOrExpired(results.GetDirectoryEntry());
if (isAccountLocked)
Console.WriteLine(targetUserName + "'s account is locked or has expired.");
else
Console.WriteLine(targetUserName + "'s account is not locked or expired.");
Console.WriteLine("\nEnter bye to exit.");
Console.WriteLine("Press any key to continue.\n\n");
}
else if (results == " ")
{
//no user entered
Console.WriteLine("No input detected!");
Console.WriteLine("\nEnter bye to exit.");
Console.WriteLine("Press any key to continue.\n");
}
else
{
//user does not exist
Console.WriteLine("User not found!");
Console.WriteLine("\nEnter bye to exit.");
Console.WriteLine("Press any key to continue.\n");
}
If it helps, I've attached the whole code below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.Data.SqlClient;
namespace ConsoleApplication2
{
class Program
{
const String serviceAccountUserName = "mobileuser1";
const String serviceAccountPassword = "password123$";
const int UF_LOCKOUT = 0x0010;
const int UF_PASSWORD_EXPIRED = 0x800000;
static void Main(string[] args)
{
string line;
Console.WriteLine("Welcome to account validator V1.0.\n"+"Please enter the ldap address to proceed.");
Console.Write("\nEnter address: ");
String ldapAddress = Console.ReadLine();
try
{
if (ldapAddress != null)
{
Console.WriteLine("\nQuerying for users in " + ldapAddress);
//start of do-while
do
{
Console.WriteLine("\nPlease enter the user's account name to proceed.");
Console.Write("\nUsername: ");
String targetUserName = Console.ReadLine();
bool isValid = false;
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, ldapAddress))
{
// validate the credentials
isValid = pc.ValidateCredentials(serviceAccountUserName, serviceAccountPassword);
// search AD data
DirectoryEntry entry = new DirectoryEntry("LDAP://" + ldapAddress, serviceAccountUserName, serviceAccountPassword);
//create instance fo the directory searcher
DirectorySearcher desearch = new DirectorySearcher(entry);
//set the search filter
desearch.Filter = "(&(sAMAccountName=" + targetUserName + ")(objectcategory=user))";
//find the first instance
SearchResult results = desearch.FindOne();
if (results != null)
{
//Check is account activated
bool isAccountActived = IsActive(results.GetDirectoryEntry());
if (isAccountActived) Console.WriteLine(targetUserName + "'s account is active.");
else Console.WriteLine(targetUserName + "'s account is inactive.");
//Check is account expired or locked
bool isAccountLocked = IsAccountLockOrExpired(results.GetDirectoryEntry());
if (isAccountLocked) Console.WriteLine(targetUserName + "'s account is locked or has expired.");
else Console.WriteLine(targetUserName + "'s account is not locked or expired.");
Console.WriteLine("\nEnter bye to exit.");
Console.WriteLine("Press any key to continue.\n\n");
}
else if (results == " ")
{
//no user entered
Console.WriteLine("No input detected!");
Console.WriteLine("\nEnter bye to exit.");
Console.WriteLine("Press any key to continue.\n");
}
else
{
//user does not exist
Console.WriteLine("User not found!");
Console.WriteLine("\nEnter bye to exit.");
Console.WriteLine("Press any key to continue.\n");
}
}//end of using
}//end of do
//leave console when 'bye' is entered
while ((line = Console.ReadLine()) != "bye");
}//end of if for ldap statement
else if (ldapAddress == " ")
{
Console.WriteLine("No input detected.");
Console.ReadLine();
Console.WriteLine("\nEnter bye to exit.");
Console.ReadLine();
Console.WriteLine("Press any key to continue.\n");
Console.ReadLine();
}
else
{
Console.WriteLine("Address not found!");
Console.ReadLine();
Console.WriteLine("\nEnter bye to exit.");
Console.ReadLine();
Console.WriteLine("Press any key to continue.\n");
Console.ReadLine();
}
}//end of try
catch (Exception e)
{
Console.WriteLine("Exception caught:\n\n" + e.ToString());
}
} //end of main void
static private bool IsActive(DirectoryEntry de)
{
if (de.NativeGuid == null) return false;
int flags = (int)de.Properties["userAccountControl"].Value;
return !Convert.ToBoolean(flags & 0x0002);
}
static private bool IsAccountLockOrExpired(DirectoryEntry de)
{
string attribName = "msDS-User-Account-Control-Computed";
de.RefreshCache(new string[] { attribName });
int userFlags = (int)de.Properties[attribName].Value;
return userFlags == UF_LOCKOUT || userFlags == UF_PASSWORD_EXPIRED;
}
}
}
You should put the ReadLine in a loop.
string UserName = "";
do {
Console.Write("Username: ");
UserName = Console.ReadLine();
if (!string.IsNullOrEmpty(UserName)) {
Console.WriteLine("OK");
} else {
Console.WriteLine("Empty input, please try again");
}
} while (string.IsNullOrEmpty(UserName));
You basically repeat the prompt over and over until the string entered by the user is no longer null or empty.
Best method would probably be to create a new function to get a non empty input:
private static string GetInput(string Prompt)
{
string Result = "";
do {
Console.Write(Prompt + ": ");
Result = Console.ReadLine();
if (string.IsNullOrEmpty(Result)) {
Console.WriteLine("Empty input, please try again");
}
} while (string.IsNullOrEmpty(Result));
return Result;
}
You can then just use the function to get your inputs like:
static void Main(string[] args)
{
GetInput("Username");
GetInput("Password");
}
Result:
Try using the code :
(!string.IsNullOrEmpty(input));
This is user first name and last name string
//Make container for the user first name and last name
string myFirstName = "";
string myLastName = "";
//Do while loop
do
{
//Welcomes user to the app and asks for first name then asks for last name
Console.WriteLine("Welcome");
Console.WriteLine("Enter first name: ");
//Takes users first name and last name and saves it in myFirstName and myLastName
myFirstName = Console.ReadLine();
Console.Write("Enter Last name: ");
myLastName = Console.ReadLine();
Console.WriteLine();
//If the first AND (&&) last name is not empty because the user entered first name and last name then display the hello message
if (!string.IsNullOrEmpty(myFirstName) && !string.IsNullOrEmpty(myLastName))
{
Console.WriteLine("Hello " + myFirstName + " " + myLastName + " hope you enjoy your day");
}
else //Else the first name or last name is left empty then display the error message
{
Console.WriteLine("Please enter your first name and last name");
Console.WriteLine();
}
//While if either the first name OR (||) last name is empty then keep asking the user for input
} while (string.IsNullOrEmpty(myFirstName) ||
string.IsNullOrEmpty(myLastName));
Console.ReadLine();
Output:
I have two classes "allmethods.cs" and "caller.cs"
I have two methods in the "allmethods.cs" class which are "WritingMethod" and "ReadingMethod"
The program should write and read from a text file. It writes smoothly when I call the "WritingMethod" but When I call the "ReadingMethod" it shows null as if there is no data in the text file.
I can't identify the problem in my code, I'd be glad if anyone help me identify the problem.
Here is my code:
public class allmethods
{
private static string Name;
private static int ID;
private static int Age;
private static string Email;
private static string output;
public static void WritingMethod()
{
int count = 0;
while (count < 2)
{
Console.Write(" Enter your Name: ");
Name = Console.ReadLine();
Console.Write(" Enter your ID: ");
ID = int.Parse(Console.ReadLine());
Console.Write(" Enter your Age: ");
Age = int.Parse(Console.ReadLine());
Console.Write(" Enter your E-mail: ");
Email = Console.ReadLine();
StreamWriter Sw = new StreamWriter("fileone.txt", true);
string output = string.Format("Thank you for registration! Your Submitted information are:" + Environment.NewLine + "Name: {0}"
+ Environment.NewLine + "ID: {1}" + Environment.NewLine + "Age: {2}" + Environment.NewLine + "E-mail: {3}", Name, ID, Age, Email);
Console.WriteLine(output);
Sw.WriteLine(output + Environment.NewLine);
Console.ReadLine();
Sw.Close();
count++;
}
}
public static void ReadingMethod()
{
FileStream fsr = new FileStream("fileone.txt", FileMode.Open, FileAccess.Read);
StreamReader Sr = new StreamReader(fsr);
string line = Sr.ReadLine();
Console.WriteLine("--Reading The File--" + Environment.NewLine + output + Environment.NewLine);
Console.ReadLine();
Sr.Close();
fsr.Close();
}
}
Thank you very much. Waiting for your answers.
It seems that you have not set the variable output. You have set line variable.
public static void ReadingMethod()
{
FileStream fsr = new FileStream("fileone.txt", FileMode.Open, FileAccess.Read);
StreamReader Sr = new StreamReader(fsr);
string line = Sr.ReadToEnd();
Console.WriteLine("--Reading The File--" + Environment.NewLine + line + Environment.NewLine);
Console.ReadLine();
Sr.Close();
fsr.Close();
}
What I have modified is changed from output to line.
Hope it helps.
This is the total solution for the series of your questions:
public partial class AllMethods {
static T ReadData<T>(String prompt, T value) {
Console.Write(prompt);
return (T)Convert.ChangeType(Console.ReadLine(), typeof(T));
}
public static void WritingMethod(int timesToInput) {
using(var sw=new StreamWriter(path, true))
for(var list=items.ToArray(); timesToInput-->0; ) {
var inputs=new Dictionary<String, object>();
for(var i=0; i<list.Length; ++i) {
var item=list[i];
var prompt=String.Format(" Enter your {0}: ", item.Key);
inputs.Add(
item.Key, AllMethods.ReadData(prompt, item.Value));
}
var output=String.Format(format, inputs.Values.ToArray());
sw.WriteLine(output+Environment.NewLine);
Console.WriteLine(output);
Console.ReadLine();
}
}
public static void ReadingMethod() {
var textFromFile=
String.Join(Environment.NewLine, File.ReadAllLines(path));
Console.WriteLine(
"--Reading The File--"+Environment.NewLine+textFromFile);
Console.ReadLine();
}
static AllMethods() {
items=new Dictionary<String, object>();
// add any item with name and type default value
items.Add("Name", default(String));
items.Add("ID", default(int));
items.Add("Age", default(int));
items.Add("Email", default(String));
var prompts=items.Select(
(item, index) => String.Format("{0}: {{{1}}}", item.Key, index));
format=
"Thank you for registration! Your Submitted information are: "
+Environment.NewLine
+String.Join(Environment.NewLine, prompts.ToArray());
path="fileone.txt";
}
static Dictionary<String, object> items;
static String format, path;
}
I'd suggest that to prepare for complete code, and don't ask duplicate questions.
class Program
{
static string strFile = "Student Database.txt";
static void Main(string[] args)
{
string strInput = null; // user input string
start:
System.IO.DirectoryInfo dir = new DirectoryInfo("student_results.txt");
// Request user input as to actions to be carried out
Console.WriteLine("\nWhat do you want to do?\n" +
" 1.View Student(s)\n 2.Add a New Student\n 3.Exit program");
// Save user input to make decision on program operation
strInput = Console.ReadLine();
// Switch statement checking the saved user input to decide the action
// to be carried out
switch (strInput)
{
case "1": // choice for view file
Console.Clear();
string file = AppDomain.CurrentDomain.BaseDirectory +
#"student_results.txt";
StreamReader sr = new StreamReader(file);
string wholeFile = sr.ReadToEnd();
Console.Write(wholeFile + "");
sr.Close();
goto start;
...
}
...
}
...
}
I want this part of my code to just read the students indivially and relay them back to me, instead of how it is doing so at the moment were it just calls all of them back to me when I press '1) view Student' it pretty much says "please enter the students name or ID number of which student you would like to view".
I've currently have got the ID number running off a random number generator.
Thank you for your time guys.
Welcome to SO, first of all goto is not a good choice in C# in 99% of cases, and you'd better use loops. For your code I would save each student in a single line and at the time of reading students I would read them line by line untill I found the student.
class Program
{
static string strFile = "Student Database.txt";
static void Main(string[] args)
{
string strInput = ""; // user input string
while (strInput != "3")
{
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo("student_results.txt");
Console.WriteLine("\nWhat do you want to do?\n 1.View Student(s)\n 2.Add a New Student\n 3.Exit program"); // request user input as to actions to be carried out
strInput = Console.ReadLine(); //save user input to make decision on program operation
switch (strInput)
{
case "1":
Console.Clear();
Console.WriteLine("Enter Student ID: \n");
string file = AppDomain.CurrentDomain.BaseDirectory + #"student_results.txt";
StreamReader sr = new StreamReader(file);
string StudentID = Console.ReadLine();
string line = "";
bool found = false;
while((line = sr.ReadLine()) != null)
{
if (line.Split(',')[0] == StudentID)
{
found = true;
Console.WriteLine(line);
break;
}
}
sr.Close();
if (!found)
{
Console.WriteLine("Not Found");
}
Console.WriteLine("Press a key to continue...");
Console.ReadLine();
break;
case "2":
Console.WriteLine("Enter Student ID : ");
string SID = Console.ReadLine();
Console.WriteLine("Enter Student Name : ");
string SName = Console.ReadLine();
Console.WriteLine("Enter Student Average : ");
string average = Console.ReadLine();
string wLine = SID + "," +SName+":"+average;
file = AppDomain.CurrentDomain.BaseDirectory + #"student_results.txt";
StreamWriter sw = File.Exists(file) ? File.AppendText(file) : new StreamWriter(file);
sw.WriteLine(wLine);
sw.Close();
Console.WriteLine("Student saved on file, press a key to continue ...");
Console.ReadLine();
Console.Clear();
break;
case "3":
return;
default:
Console.Clear();
Console.WriteLine("Invalid Command!\n");
break;
}
}
}
}
this code might not be complete, I wanted to give you the idea, I hope it helps.
Presuming you are not dealing with a huge file of students, and on the basis that you want to make multiple queries, i would not read the text file line by line each time.
Instead create a student class, read the file once on init, and create a list< student > from the data. Then you can query it with LinQ
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ReadStudents
{
class Program
{
static string _filename = "students.txt";
static void Main(string[] args)
{
List<Student> students = new List<Student>();
// Load students.
StreamReader reader = new StreamReader(_filename);
while (!reader.EndOfStream)
students.Add( new Student( reader.ReadLine()));
reader.Close();
string action;
bool showAgain = true;
do
{
Console.WriteLine("");
Console.WriteLine("1. See all students.");
Console.WriteLine("2. See student by ID.");
Console.WriteLine("3. Add new student.");
Console.WriteLine("0. Exit.");
Console.WriteLine("");
action = Console.ReadLine();
switch (action)
{
case "1":
foreach (Student item in students)
item.Show();
break;
case "2":
Console.Write("ID = ");
int id = int.Parse( Console.ReadLine() ); // TODO: is valid int?
foreach (Student item in students)
if (item.Id == id)
item.Show();
break;
case "3":
Console.WriteLine("ID-Name");
Student newStudent = new Student(Console.ReadLine());
students.Add(newStudent);
StreamWriter writer = new StreamWriter(_filename, true);
writer.WriteLine(newStudent);
writer.Close();
break;
case "0":
Console.WriteLine("Bye!");
showAgain = false;
break;
default:
Console.WriteLine("Wrong action!");
break;
}
}
while (showAgain);
}
}
class Student
{
public int Id;
public string Name;
public Student(string line)
{
string[] fields = line.Split('-');
Id = int.Parse(fields[0]);
Name = fields[1];
}
public void Show()
{
Console.WriteLine(Id + ". " + Name);
}
}
}
I assume your data are in "ID-Name" format for example:
1-Alexander
2-Brian
3-Christian
I load file line-by-line and pass to Student class which converts in constructor text data to more friendly form. Next, application shows interface until user write "0".