Как написать и обновить оценку пользователя, которая хранится в текстовом файле в C #? - PullRequest
0 голосов
/ 18 февраля 2019

Я создаю игру-викторину для моего курса по вычислительной технике уровня A.Тест работает нормально, но проблема в том, что в конце теста я хочу сохранить оценку пользователей и имя пользователя в текстовом файле.Я уже пытался найти ответ как на Stack Overflow, так и на других сайтах, но не смог найти ответ.

В конце теста у меня есть форма EndForm, и когда эта форма загружается, я вызываю метод с именем SaveScore().Код ниже.Я хочу, чтобы этот метод сохранял имя пользователя и оценку пользователя в файле Scores.txt.Я также хочу, чтобы оценка пользователей обновлялась, если пользователь повторяет тест и получает более высокий балл.Я не знаю, почему мой текущий код не работает.

    private void SaveScore()
    {

        string file = @"..\..\textfiles\scores.txt";

        FileStream fileStream;
        StreamWriter streamWriter;

        try
        {
            if (File.Exists(file))
            {
                string[] HighScore = File.ReadAllLines(file).ToArray();
                string[] contents = new string[] { };
                File.WriteAllLines(file, contents);

                 fileStream = new FileStream(file, FileMode.Create, FileAccess.Write);
                 streamWriter = new StreamWriter(fileStream);

                for (int i = 0; i < HighScore.Length; i++)
                {
                    string[] HighScores = HighScore[i].Split('~');

                    string username = HighScores[0];
                    int currentScore = Convert.ToInt32(HighScores[1]);

                    if (player.Score > currentScore)
                    {
                        streamWriter.WriteLine(player.Name + "~" + player.Score);

                        for (int x = i; x < 4; x++)
                        {
                            string[] newHighScore = HighScore[x].Split('~');

                            string newUsername = newHighScore[0];
                            int newScore = Convert.ToInt32(newHighScore[1]);
                            streamWriter.WriteLine(newUsername + "~" + newScore);
                        }
                        break;
                    }

                    else
                    {
                        streamWriter.WriteLine(username + "~" + currentScore);
                    }

                    streamWriter.Close();
                    fileStream.Close();
                //Write player score data to file if it is not already there.

                    if (HighScore.Length < 10)
                    {
                        fileStream = new FileStream(file, FileMode.Append, FileAccess.Write);
                        streamWriter = new StreamWriter(fileStream);

                        streamWriter.WriteLine(player.Name + "~" + player.Score);

                        streamWriter.Close();
                        fileStream.Close();
                    }
                }
            }
        }

        catch
        {
            MessageBox.Show("Error saving high score", "Error");
        }
    }

Любая помощь будет оценена, спасибо заранее.

Ответы [ 2 ]

0 голосов
/ 18 февраля 2019

Это должно сделать все, что вам нужно - если у вас есть какие-либо вопросы, просто задавайте.Могу ли я также предложить использовать CSV, а не текстовый файл?Просто измените расширение.

private void SaveScore()
{
    String scoresFilePath = @"..\..\textfiles\scores.txt";

    try
    {
        //
        // Create file if not exists
        //
        if (!File.Exists(scoresFilePath))
        {
            File.Create(scoresFilePath).Dispose();
        }

        //
        // Create DataTable
        //
        DataColumn nameColumn = new DataColumn("name", typeof(String));
        DataColumn scoreColumn = new DataColumn("score", typeof(int));

        DataTable scores = new DataTable();
        scores.Columns.Add(nameColumn);
        scores.Columns.Add(scoreColumn);

        //
        // Read CSV and populate DataTable
        //
        using (StreamReader streamReader = new StreamReader(scoresFilePath))
        {
            streamReader.ReadLine();

            while (!streamReader.EndOfStream)
            {
                String[] row = streamReader.ReadLine().Split(',');
                scores.Rows.Add(row);
            }
        }

        Boolean scoreFound = false;

        //
        // If user exists and new score is higher, update 
        //
        foreach (DataRow score in scores.Rows)
        {
            if ((String)score["name"] == player.Name)
            {
                if ((int)score["score"] < player.Score)
                {
                    score["score"] = player.Score;
                }

                scoreFound = true;
                break;
            }
        }

        //
        // If user doesn't exist then add user/score
        //
        if (!scoreFound)
        {
            scores.Rows.Add(player.Name, player.Score);
        }

        //
        // Write changes to CSV (empty then rewrite)
        //
        File.WriteAllText(scoresFilePath, string.Empty);

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.AppendLine("name,score");

        foreach (DataRow score in scores.Rows)
        {
            stringBuilder.AppendLine(score["name"] + "," + score["score"]);
        }

        File.WriteAllText(scoresFilePath, stringBuilder.ToString());
    }

    catch(Exception ex)
    {
        MessageBox.Show("Error saving high score:\n\n" + ex.ToString(), "Error");
    }
}
0 голосов
/ 18 февраля 2019

Старайтесь не глотать исключение, и вы должны получить полезное сообщение об ошибке.Изменить:

catch
{
    MessageBox.Show("Error saving high score", "Error");
}

на

catch(Exception ex)
{
    MessageBox.Show("Error saving high score: " + ex.ToString(), "Error");
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...