【问题标题】:Writing to a text file in C#, but there is an exception unhandled error在 C# 中写入文本文件,但出现异常未处理错误
【发布时间】:2019-02-05 21:21:25
【问题描述】:

我一直在做一个测验,并想实施一个排行榜。排行榜应该显示用户的名字,分数

我检查了它是否正在识别文件,当我删除分数时它工作正常。当我以所有其他形式在标签上显示分数时,分数工作正常。

公共部分类frmLeaderboard:表格 {enter code here //设置播放器列表 列出玩家 = new List();

    public frmLeaderboard()
    {
         //Setup form
         InitializeComponent();
         dgLeaderboard.ColumnCount = 3;
         dgLeaderboard.Columns[0].Name = "Player Name";
         dgLeaderboard.Columns[1].Name = "Score"; 
         dgLeaderboard.Columns[2].Name = "Level";
         SaveScores();
         GetPreviousPlayers();
    }

    private void GetPreviousPlayers()
    {
        //searches for file and loads score
        if(File.Exists("previousplayers.txt"))
        {
            LoadScores();
        }

        dgLeaderboard.Sort(dgLeaderboard.Columns[1], ListSortDirection.Descending);
    }

    private void LoadScores()
    {
        if (File.Exists("previousplayers.txt"))
        {
            //Loads the score
            var playerScores = File.ReadAllLines("previousplayers.txt");

            if (playerScores.Length > 0)
            {
                //bring in the players to the grid
                foreach (var players in playerScores)
                {
                    var splitDetails = players.Split('~');
                    dgLeaderboard.Rows.Add(splitDetails[0], Convert.ToInt32(splitDetails[0]), splitDetails[2]);
                }
            }

            else
            {
                HideGrid();
            }
        }
    }

    private void SaveScores()
    {
        FileStream fileStream = new FileStream("previousplayers.txt", FileMode.Append, FileAccess.Write);
        StreamWriter streamWriter = new StreamWriter(fileStream);

        //Seperate the username, score and level
        try
        {
            foreach(var player in players)
            {
                streamWriter.WriteLine(player.Username + "~" + player.Score + "~" + player.Level);
            }
        }
        catch(Exception)
        {
            MessageBox.Show("Error Loading the scores", "Please try again");
        }
        finally
        {
            streamWriter.Close();
            fileStream.Close();
        }

    }

    private void HideGrid()
    {
        //Sets the grid to invisible
        dgLeaderboard.Visible = false;
    }



}

在我使用此代码之前的表单中

string filePath = "previousplayers.txt";
        FileStream aFile;
        StreamWriter sw;

        try
        {`enter code here`
            if (!File.Exists(filePath))
            {
                aFile = new FileStream(filePath, FileMode.Create, FileAccess.Write);
            }
            else
            {
                aFile = new FileStream(filePath, FileMode.Append, FileAccess.Write);
            }

            sw = new StreamWriter(aFile);
            sw.WriteLine(frmStart.Player.Username + "~" + frmStart.Player.Score + "~" + frmStart.Player.Level);
            sw.Close();
            aFile.Close();

        }
        catch (Exception ex)
        {
            MessageBox.Show("User's details have not been saved", "Error Occurred");
        }

它因错误而崩溃:Exception Unhandled, System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'

在这一行 dgLeaderboard.Rows.Add(splitDetails[0], Convert.ToInt32(splitDetails[0]), splitDetails[2]);

块引用

【问题讨论】:

  • 发生该错误是因为您向数组索引器提供的索引太大(>=数组大小)或负数。
  • 另外,请注意您不需要检查File.Exists(filePath)。如果文件不存在,FileMode.Append 将创建该文件。 + Convert.ToInt32(splitDetails[0]): splitDetails[0] 在这里是一个字符串,包含player.Username,因为:streamWriter.WriteLine(player.Username + "~" (...)。除非您混合不同的版本程序。

标签: c# winforms datagrid


【解决方案1】:

你是这样写球员分数的:

player.Username + "~" + player.Score + player.Level

因此,如果您正在阅读它并将其拆分为 ~,您将得到一个长度为 2 的数组,其中 [0] 是 player.Username,[1] 是 player.Score + player.level。您正在尝试访问超出范围的索引 [2]。

【讨论】:

  • 嗯,我在和相同的错误显示之间添加了额外的“~”
  • 改格式后记得删除旧文件吗?否则,即使新行格式正确,解析旧行仍然会抛出。
  • 另外,您尝试将用户名写入第一列和第二列是不是一个错误?我认为应该是dgLeaderboard.Rows.Add(splitDetails[0], Convert.ToInt32(splitDetails[1]), splitDetails[2]);
  • 这里一定是打错了,因为我的代码就是这样
  • 好极了,很高兴听到它!
猜你喜欢
  • 2021-12-08
  • 1970-01-01
  • 1970-01-01
  • 2011-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-21
  • 1970-01-01
相关资源
最近更新 更多