i want to know how i can delete file without the System.IO.IOException it keeps saying that "System.IO.IOException: 'The process cannot access the file 'C:\A1\AccNum.txt' because it is being used by another process.'"
private static void deleteaccount()
{
int accountNum2;
string accountVar = string.Empty;
const int MaxLength = 10;
string line2;
Console.WriteLine("DELETE AN ACCOUNT");
Console.WriteLine("=================");
Console.WriteLine("ENTER THE DETAILS");
Console.WriteLine("");
Console.WriteLine("Account Number: {0}", accountVar);
accountVar = Console.ReadLine();
Console.WriteLine("=================");
try
{
accountNum2 = Convert.ToInt32(accountVar);
}
catch (OverflowException ex)
{
Console.WriteLine("The Error is {0}: ", ex);
}
finally
{
if (accountVar.Length < MaxLength && accountVar.Length > 5)
{
System.IO.StreamReader file = new System.IO.StreamReader(@"C://A1//AccNum.txt");
while ((line2 = file.ReadLine()) != null)
if (line2.Contains(accountVar))
{
Console.WriteLine("Account Found! Details display below...");
string text2 = File.ReadAllText(@"C://A1//AccNum.txt");
Console.WriteLine(text2);
Console.WriteLine("=================");
Console.WriteLine("");
Console.Write("Delete? (y/n): ");
string answer2;
answer2 = Console.ReadLine();
if ((answer2.Contains("y") || answer2.Contains("Y")))
{
if (File.Exists(@"C://A1//AccNum.txt"))
{
File.Delete(@"C://A1//AccNum.txt"); // This part says it has 'System.IO.IOException: 'The process cannot access the file 'C:\A1\AccNum.txt' because it is being used by another process.''
}
Console.Write("Account Deleted!...");
Console.Read();
ShowMainMenu();
break;
}
StreamReaderstill has the file open. This code overall is not very clear, and you keep re-reading the same file over and over, all while keeping another reader open on the file. How many times do you really need to read the same file? What exactly is this code attempting to do? It looks like you don't need or want theStreamReaderat all. You can just read the whole file into memory (withReadAllTextorReadAllLinesor anything of that nature) and perform all of your logic on that in-memory data. Then you won't have any file handles open and can delete it whenever you want.finallyblock - there is a lot that could be going wrong in there. That said, if you take the advice from the other folks then I'd expect your method will be a lot smaller / simpler.