1

I saw other threads about this problem, and non of them seems to solve my exact problem.

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);
            }
        }

So after I run the program and get to that point in code I get an error message: "The process cannot access the file 'fileName/textFile.txt' because it is being used by another process."

Bor1s
  • 13
  • 2
  • 2
    What is "that point in code"? You are `Flush()`ing `streamWriter` but never `Close()`ing or `Dispose()`ing it. You should be calling `Close()`, by the way, inside a `finally` block to ensure it's executed even if an exception is thrown first. Better still, as @Steve recommends, that scenario is what the `using` statement and `using` declaration are for. – Lance U. Matthews May 22 '22 at 20:55

1 Answers1

1

You should use the using statement around disposable objects like streams. This will ensure that the objects release every unmanaged resources they hold. And don't open the writer until you need it. Makes no sense to open the writer when first you need to read the records

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
    }
}

Also you should consider that working with files is one of the most probable context in which you could receive an exception due to external events in which your program has no control.
It is better to enclose everything in a try/catch block with proper handling of the exception

Steve
  • 213,761
  • 22
  • 232
  • 286
  • After adding a `using` statement, try/catch should only be used if logging or handling the error reasonably makes sense. In other cases all you are doing is swallowing exceptions that provide critical clues for debugging. – NightOwl888 May 22 '22 at 21:17