【发布时间】:2016-10-11 22:05:08
【问题描述】:
我在从文件读取到列表时遇到了一些问题。 文件内容是这样的:
[ROOM101]
that way this way no way all the way
[END]
[ROOM102]
all the way that way this way no way
[END]
[ROOM103]
no way all the way that way this way
[END]
方法如下:
public static List<Room> ReadRooms(string path)
{
List<Room> rooms = new List<Room>();
StreamReader reader = new StreamReader(path);
bool roomsLeft = true;
char currentChar;
string directions;
StringBuilder builder = new StringBuilder();
while (roomsLeft) {
currentChar = (char)reader.Read();
if (currentChar == '[') {
currentChar = (char)reader.Read();
while (currentChar != ']') {
builder.Append(currentChar);
currentChar = (char)reader.Read();
}
if (builder.ToString() != "END") {
directions = reader.ReadLine();
rooms.Add(new Room(builder.ToString(), directions));
}
}
if (reader.EndOfStream) {
roomsLeft = false;
}
}
reader.Close();
return rooms;
}
它可以很好地读取第一行,但directions = ReadLine() 绝对没有返回任何内容,并且没有任何内容被添加到列表中 - 它不应该跳转到下一行并分配给directions吗?整个事情的结果是StackOverflowException。
【问题讨论】:
-
因为您阅读的最后一件事是
],而不是换行符。为什么不读取这些行,只检查该行是否以[开头并以]结尾,或者它是否是“[END]”而不是尝试一次读取一个字符? -
代码向后看。你怎么知道还有没有读档的房间?通常你会在 StreamReader 上循环直到你到达 null (End Of File)。
-
我建议将新行读入一个变量,然后在该行上执行您的逻辑,因为流阅读器将从您之前的读取读取到下一个新行字符
标签: c# list file streamreader