C# 索引自动失效例外
为什么会出现C# 索引自动失效例外,c#,arrays,exception,exception-handling,file.readalllines,C#,Arrays,Exception,Exception Handling,File.readalllines,为什么会出现索引自动失效异常 string[] achCheckStr = File.ReadAllLines("achievements.txt"); if (achCheckStr[0] == ach1_StillBurning) // this is where the exception occurs { setAchievements(1); } if (achCheckStr[1] == ach2_Faster) { setAchievements(2); } 您
索引自动失效
异常
string[] achCheckStr = File.ReadAllLines("achievements.txt");
if (achCheckStr[0] == ach1_StillBurning) // this is where the exception occurs
{
setAchievements(1);
}
if (achCheckStr[1] == ach2_Faster)
{
setAchievements(2);
}
您的代码假设
achCheckStr
数组至少有2个元素,而不首先检查元素的数量。如果文件存在且内容为空,achCheckStr.Length
将为0,IndexOutOfRangeException
将在发生异常的地方抛出。问题1:
可能不存在名为acgregations.txt
的文件。
此语句string[]achCheckStr=File.ReadAllLines(“acquisitions.txt”)
可能返回null
解决方案1:因此,在访问任何文件之前,请使用file.exists()
方法检查文件是否存在
问题2:文本文件中可能没有行
解决方案2:在访问包含行的字符串数组之前,请通过检查其长度来确保它不是空的
试试这个:
if(File.Exists("achievements.txt"))
{
string[] achCheckStr = File.ReadAllLines("achievements.txt");
if(achCheckStr.Length > 0)
{
if (achCheckStr[0] == ach1_StillBurning)
{
setAchievements(1);
}
if (achCheckStr[1] == ach2_Faster)
{
setAchievements(2);
}
}
}
你在哪里存储“aclements.txt”?它可能位于错误的位置,因此代码无法找到它
您可以完全限定路径或将文件放在生成.exe的bin目录中 这里有一个方法
string[] achCheckStr = File.ReadAllLines("achievements.txt");
if (achCheckStr != null && achCheckStr.Any())
{
if (achCheckStr[0] == ach1_StillBurning) // this is where the exception occurs
{
setAchievements(1);
}
if (achCheckStr[1] == ach2_Faster)
{
setAchievements(2);
}
}
您是否已验证使用调试器实际获取文件的内容?添加以下内容:如果(achCheckStr!=null)在i(achCheckStr[0]==…..之前添加断点并验证achCheckStr
是否有数据。。。