[英]How can i fix the 'System.IO.IOException: 'The process cannot access the file'
我想知道如何在沒有System.IO.IOException的情況下刪除文件,它一直說“ System.IO.IOException:'該進程無法訪問文件'C:\\ A1 \\ AccNum.txt',因為該文件正在被使用另一個過程。”
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;
}
您正在使用文件(使用閱讀器),除非停止使用,否則無法將其刪除。
在if塊內關閉閱讀器,然后嘗試刪除該文件。
使用File.ReadAllText時,您不需要關閉任何內容(以及在File的其他靜態成員中),但是對於StreamReader,您需要自己關閉流。
Ps您還應該重構代碼,因為它有缺陷。
您的代碼兩次打開AccNum.txt文件。 在打開文件時,同時嘗試刪除觸發IOException的文件。
如果要刪除文件,請確保沒有其他程序打開文件。 您尚未打開要刪除的文件的文件句柄。 在您的程序中,您就是在刪除文件的同時打開文件的人。 因此,首先釋放文件句柄。
if (File.Exists(@"C://A1//AccNum.txt"))
{
// file is your StreamReader.
file.Close();
file.Dispose();
File.Delete(@"C://A1//AccNum.txt");
}
另請注意,如果在文件中找到accountVar
打開同一文件2次或多次。 更好的選擇是堅持使用單個File.ReadAllText()
調用並使用該內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.