我的代码:
using (StreamReader sr = new StreamReader("Flash Disk/thing.ini"))
{
text = sr.ReadToEnd();
int length = text.Length; //3722
int indexStart = text.IndexOf("DeviceName="); //3126
int indexEnd = text.IndexOf("DeviceID="); //3145
string deviceName = text.Substring(indexStart, indexEnd);
Console.WriteLine(name);
}
它在字符串deviceName = text.Substring(indexStart,indexEnd)中爆炸;
我收到了ArgumentOutOfRangeException,它告诉我'指定的参数超出了有效值的范围。'没有其他的。
我迷失在这里。有任何想法吗?
在你的问题中,总字符串长度是4752
int length = text.Length; //4752
但Substring第二个参数号表示您要检索的字符数。
在你的代码中,以indexStart(4176)
开头并检索将超过字符串Length的indexEnd(4195)
。
我想你需要在第二个参数上使用indexEnd - indexStart
int indexStart = text.IndexOf("DeviceName="); //4176
int indexEnd = text.IndexOf("DeviceID="); //4195
string deviceName = text.Substring(indexStart, indexEnd - indexStart);