[英]StringReader not “exiting”/breaking
我在使用以下代码时遇到问题…当我运行它时,代码永不退出。 我已经尝试调试了大约一个小时,但对于问题所在,我完全不知所措。 OutputDebug(); 本质上类似于Console.WriteLine();
//Iterate through all lines to find sections
using (StringReader lineReader = new StringReader(Program))
{
int i = 0;
string line = string.Empty;
while (line != null)
{
line = lineReader.ReadLine();
if (line != string.Empty)
{
//If the program is exiting (doExit == true), then break the lööp bröther
if (doExit)
break;
//Iterate through all characters in the line
foreach (char Character in line)
{
i++;
OutputDebug(i.ToString());
if (isOnSameLineAsSectionStart)
{
sectionName += Character;
}
else if (Character == ':' && sectionName == string.Empty)
{
isOnSameLineAsSectionStart = true;
}
else if (Character == ':' && !isOnSameLineAsSectionStart && sectionName != string.Empty)
{
OutputDebug("End of section \"" + sectionName + "\" found");
OutputDebug(linesInSection.Count() + " lines found total in " + sectionName + "\" during section search");
try
{
sections.Add(sectionName, linesInSection);
}
catch (Exception)
{
OutputError("Two/Multiple sections with the same names exist. Ignoring the latest section with the same name");
}
linesInSection = new List<string>();
sectionName = string.Empty;
isOnSameLineAsSectionStart = true;
}
}
if (!isOnSameLineAsSectionStart && sectionName != string.Empty)
{
linesInSection.Add(line);
}
if (isOnSameLineAsSectionStart && sectionName != string.Empty)
{
OutputDebug("Start of section \"" + sectionName + "\" found");
}
if (isOnSameLineAsSectionStart == true)
{
isOnSameLineAsSectionStart = false;
}
}
lineReader.Close();
OutputDebug("In StringReader!" + i);
}
提前致谢!
您可以在下面使用while方法:
while ((line = reader.ReadLine()) != null)
{
foreach (char Character in line)
{
i++;
OutputDebug(i.ToString());
}
}
好吧,如果要逐行输出所有字符。 您可以将它们拆分为字符串数组:
var lines = Regex.Split(input, "\\r\\n|\\r|\\n")
从此处提取。
稍后,使用foreach而不是while语句,您应该可以解决问题:
foreach(string line in lines)
还将字符串与空值进行比较...看起来不太好。 为什么不使用(内置) string.IsNullOrEmpty(line)
方法检查当前行是否为空?
如果要使用您的方法,则应执行以下操作:
while (!string.IsNullOrEmpty(line = reader.ReadLine()))
{
// Your code...
}
希望这可以帮助!
由于我们仅限于此片段,因此我们只能做一些假设。
lineReader.ReadLine();
如果这是一个阻塞调用,则只要没有输入,代码就永远不会退出。
如果这是一个取消阻塞的调用,则意味着即使没有提供输入,它也会返回一些内容。 如果在这种情况下返回的值为空字符串,则说明您处于无限循环中。
我相信这里的关键功能是ReadLine
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.