Хранение данных в файле и IOException (процесс не может получить доступ к файлу) - C#
Формулировка задачи:
Просто себе играюсь и решил проделать все шаги верификации. Возникла проблема при созданию нового пользователя. Если он введет имя и оно занято, программа снову предлагает ему ввести новое имя и проделав весь путь, в конце возникнет ошибка (IOException не обработано - Процесс не может получить доступ к файлу "Z:\Test.txt", так как этот файл используется другим процессом.) и соответственно данные не сохраняться. Как это исправить? Проблема в методе WriteAccauntDataInTXT();
Если пользователь введет имя которого нету в списке, программа все отлично принимает.
Листинг программы
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.IO;
- namespace Accaunt
- {
- class AccauntCheck
- {
- string accaunt;
- string password;
- string passwordAgain;
- string info;
- Random rand = new Random();
- public void AccauntCreate()
- {
- Console.Write("Hello! Enter your new account name - ");
- accaunt = Convert.ToString(Console.ReadLine());
- using (StreamReader sr = new StreamReader("Test.txt"))
- {
- string line = sr.ReadToEnd();
- if (!line.Contains(accaunt))
- {
- CheckIfAccountNameFree();
- }
- else
- {
- Console.ForegroundColor = ConsoleColor.Red;
- Console.WriteLine("Sorry! This nickname was taken. Try another one\n");
- Console.ForegroundColor = ConsoleColor.Gray;
- AccauntCreate();
- }
- }
- WriteAccauntDataInTXT();
- }
- public void WriteAccauntDataInTXT()
- {
- Console.WriteLine(info);
- using (StreamWriter sw = new StreamWriter("Test.txt", true))
- {
- sw.WriteLine(info);
- }
- }
- public void CheckIfAccountNameFree()
- {
- Console.Write("\nNow create you password - ");
- password = Convert.ToString(Console.ReadLine());
- Console.Write("One more time password - ");
- passwordAgain = Convert.ToString(Console.ReadLine());
- Console.WriteLine();
- CheckPassword();
- }
- public void CheckPassword()
- {
- if (password == passwordAgain)
- {
- int randomCode = rand.Next(1000, 10000);
- //Console.Write("To validate your account enter this code: " + randomCode + "\nCode: ");
- Console.Write("To validate your account enter this code: ");
- Console.ForegroundColor = ConsoleColor.Green;
- Console.Write(randomCode);
- Console.ForegroundColor = ConsoleColor.Gray;
- Console.Write("\nCode: ");
- int validateCode = Convert.ToInt32(Console.ReadLine());
- if (randomCode == validateCode)
- {
- info = "account name - " + accaunt + " " + "\npassword - " + password;
- string[] data = { info };
- }
- else
- {
- Console.WriteLine("\nYou enter wrong code. Try one more time!\n");
- CheckPassword();
- }
- }
- else
- {
- Console.ForegroundColor = ConsoleColor.Red;
- Console.WriteLine("Password is different! Enter it again.");
- Console.ForegroundColor = ConsoleColor.Gray;
- CheckIfAccountNameFree();
- }
- return;
- }
- public void AccauntEnter()
- {
- Console.Write("Enter your NickName: ");
- accaunt = Convert.ToString(Console.ReadLine());
- Console.Write("Enter your password: ");
- password = Convert.ToString(Console.ReadLine());
- using (StreamReader sr = new StreamReader("Test.txt"))
- {
- string checkSR = sr.ReadToEnd();
- if (checkSR.Contains(accaunt) == true)
- {
- if (checkSR.Contains(password) == true)
- {
- Console.WriteLine("Welcome back " + accaunt + "!");
- }
- else
- {
- Console.WriteLine("\nWrong password! Try one more time");
- AccauntEnter();
- }
- }
- else
- {
- Console.WriteLine("This user doesn't existe.\n");
- Operations.StartProgram();
- }
- }
- }
- }
- class Operations
- {
- public static void StartProgram()
- {
- AccauntCheck ac = new AccauntCheck();
- Console.WriteLine("Hello! Are you new customer or you have an account?");
- Console.WriteLine("1 - I have account\n2 - Create new account");
- string choise = Convert.ToString(Console.ReadLine());
- if (choise == "1")
- {
- ac.AccauntEnter();
- }
- else if (choise == "2")
- {
- ac.AccauntCreate();
- }
- else
- {
- Console.WriteLine("Error! Try one more time!");
- }
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- Operations.StartProgram();
- Console.ReadLine();
- }
- }
- }
Решение задачи: «Хранение данных в файле и IOException (процесс не может получить доступ к файлу)»
textual
Листинг программы
- public void AccauntCreate()
- {
- string lines = String.Empty; // сюда запишем строки из файла
- Console.Write("Hello! Enter your new account name - ");
- accaunt = Convert.ToString(Console.ReadLine());
- using (StreamReader sr = new StreamReader("Test.txt"))
- {
- lines = sr.ReadToEnd(); // считаем их и закроем поток
- }
- if (!lines.Contains(accaunt)) // если имени нету задаём пароль и записываем в файл, иначе запускаем заново процесс ввода имени
- {
- CheckIfAccountNameFree();
- WriteAccauntDataInTXT();
- }
- else
- {
- Console.ForegroundColor = ConsoleColor.Red;
- Console.WriteLine("Sorry! This nickname was taken. Try another one\n");
- Console.ForegroundColor = ConsoleColor.Gray;
- AccauntCreate();
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д