I am writing a program that takes user input and writes it to a CSV file. I am also checking to see if what they have input is a duplicate of whatever is in that CSV file. So far, the flow of this code snippet is:
- Get user input ->
- Iterate through the CSV file and assign it to a list ->
- If the list is empty (null) or if it doesn't contain a username ->
- Write data to CSV.
- If user input is a duplicate -> don't write
I'm a bit new to OOP and C# in general, so any tips would be appreciated.
private string writeUser()
{
string filePath = "usernames.csv";
List<string> users = new List<string>();
try
{
using (StreamReader sr = new StreamReader(filePath))
{
while (sr.Peek() >= 0) // iterate through the csv and add it to our users list
{
users.Add(sr.ReadLine());
}
sr.Close();
}
using (StreamWriter sw = new StreamWriter(filePath, true))
{
if (users == null | !users.Contains(this.username)) // write to csv if users is empty, or if it doesnt contain the typed username
{
sw.WriteLine(this.username);
sw.Close();
}
else if (users.Contains(this.username))
{
Console.WriteLine("username already exists");
sw.Close();
}
}
}
catch (Exception e)
{
Console.WriteLine("Some Error Occured: \n" + e.Message);
Console.ReadLine();
}
return this.username;
}
How can I simplify this/make what I have better?
using
blocks will take care of theClose
method calls, you don't have to callsr.Close
andsw.Close
explicitly. \$\endgroup\$