简体   繁体   中英

index out of bounds of the array

string[] scores = File.ReadAllLines(@"text file");
string score1 = scores[0];

The textfile contains the values 1-10 yet it keeps telling me the index is out of range.

why is this?

ReadAllLines is returning an array of length 0. Either your path to the file is bad or the file doesn't have what you expect in it. On the line where you index into 0 if you instead try printing the length of scores and you'll find it is 0.

In general you should be checking the length or using a foreach or for loop bound by the collections length so that you can avoid these types of exceptions. However, that being said, you need to follow that path and confirm whats in the file here. Keep in mind if you're using a relative path the Current working directory when the program is running might be different than what you expected.

Use something like this

string[] lines = File.ReadAllLines("C:\\rearrange.txt");// whatever your name of file is and the location

The ReadAllLines does not know the exact location where to read the data from

If it keeps telling you the index is out of range, it's probably because it actually is out of range - your array has length 0. Are you sure the contents of the file are what you think they are?

You should probably give the documentation a thorough read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM