簡體   English   中英

IOException:該進程無法訪問文件“fileName/textFile.txt”,因為它正被另一個進程使用

[英]IOException: The process cannot access the file 'fileName/textFile.txt' because it is being used by another process

我看到了關於這個問題的其他線程,但似乎沒有一個能解決我的確切問題。

static void RecordUpdater(string username,int points,string term) //Updates Record File with New Records.
        {
            int minPoints = 0;
            StreamWriter streamWriter = new StreamWriter($@"Record\{term}");
            Player playersRecord = new Player(points, username);
            List<Player> allRecords = new List<Player>();
            StreamReader reader = new StreamReader($@"Record\{term}");
            while (!reader.EndOfStream)
            {
                string[] splitText = reader.ReadLine().Split(',');
                Player record = new Player(Convert.ToInt32(splitText[0]), splitText[1]);
                allRecords.Add(record);
            }
            
            reader.Close();

            foreach (var playerpoint in allRecords )
            {
                if(minPoints > playerpoint.points)
                    minPoints = playerpoint.points;
            }
            if (points > minPoints)
            {

                allRecords.Add(playersRecord);
                allRecords.Remove(allRecords.Min());
            }
            allRecords.Sort();
            allRecords.Reverse();
            streamWriter.Flush();
            foreach (var player in allRecords)
            {
                streamWriter.WriteLine(player.points + "," + player.username);
            }
        }

因此,在我運行程序並在代碼中到達該點后,我收到一條錯誤消息:“該進程無法訪問文件'fileName/textFile.txt',因為它正在被另一個進程使用。”

您應該在流等一次性對象周圍使用using 語句 這將確保對象釋放它們持有的所有非托管資源。 在你需要之前不要打開作家。 當您首先需要閱讀記錄時打開編寫器是沒有意義的

static void RecordUpdater(string username,int points,string term) 
{
    Player playersRecord = new Player(points, username);
    List<Player> allRecords = new List<Player>();
    int minPoints = 0;
    try
    {
        using(StreamReader reader = new StreamReader($@"Record\{term}"))
        {
            while (!reader.EndOfStream)
            {
                .... load you data line by line
            }
        }        

        ..... process your data .....

        using(StreamWriter streamWriter = new StreamWriter($@"Record\{term}"))
        {
            ... write your data...
        }
    }
    catch(Exception ex)
    {
        ... show a message about the ex.Message or just log everything
            in a file for later analysis
    }
}

此外,您應該考慮使用文件是最可能的上下文之一,在這種情況下,由於您的程序無法控制的外部事件,您可能會收到異常。
最好將所有內容都包含在try/catch塊中,並正確處理異常

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM