public static void Main()
{
string username = "", password, chkusername;
bool vald, chk;
vald = false;
string choice = "Y";
while (choice == "Y")
{
FileStream fs = new FileStream("Users.txt", FileMode.Append,
FileAccess.Write, FileShare.Read);
StreamWriter sw = new StreamWriter(fs);
Console.WriteLine("Enter Username : ");
var Createnew = File.ReadAllLines("Users.txt");`
chkusername = Console.ReadLine();
foreach(string Dummies in Createnew)
{
string[] userline = Dummies.Split('#');
if(userline[0].Equals(chkusername))
{
vald = true;
Console.Clear();
Console.WriteLine("username already exists please choose another");
Console.ReadKey();
Console.Clear();
break;
}
chk = vald;
if (vald == true)
{
Main();
}
while(choice == "Y")
{
username = chkusername;
Console.WriteLine("Enter a Password : ");
password = Console.ReadLine();
sw.WriteLine(username + "#" + password);
sw.Flush();
sw.Close();
fs.Close();
Console.WriteLine("Username Created");
Console.WriteLine("Do you want to continue ? Y/N");
choice = Console.ReadLine();
}
}
}
}
I get an exception here:
var Createnew = File.ReadAllLines("Users.txt");
System.IO.IOException: 'The process cannot access the file 'C:\Users\admin1\source\repos\LumberJackProgram\LumberJackProgram\Users.txt' because it is being used by another process.'
First process the Users.txt file storing each name in an HashSet collection of strings
HashSet<string> names = new HashSet<string>();
var lines = File.ReadAllLines("Users.txt");
foreach(string line in lines)
{
string name = line.Split('#')[0];
if(!names.Contains(name))
names.Add(name);
}
Now you can ask your user to enter the information needed and check against the HashSet if the name is already there or not
while (choice == "Y")
{
Console.WriteLine("Enter Username : ");
chkusername = Console.ReadLine();
if(names.Contains(chkusername))
Console.WriteLine("Name already entered");
else
{
Console.WriteLine("Enter a Password : ");
password = Console.ReadLine();
names.Add(chkusername);
// Write the file in append mode and close/dispose it
using(StreamWriter sw = new StreamWriter("Users.txt",true))
sw.WriteLine(chkusername + "#" + password);
}
Console.WriteLine("Continue? Y/N");
choice = Console.ReadLine();
}
In this way you don't mix the reading part with the writing part. Also you don't need to recall the Main method to reenter this code if the name exists in your file
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments