内部While循环只运行一次
本文关键字:一次 运行 While 循环 内部 | 更新日期: 2023-09-27 18:26:00
代码的目的是在字符串(另一个文档)的长列表中查找字符串(来自一个文档的)的一部分,并将结果返回到列表中。
我有两个while循环,一个嵌套在另一个中。外部循环读取该文档的每一行,内部循环读取其文档的每个循环。出于某种原因,内部while只运行一次(对于外部循环的第一次迭代)。你能解释一下我为什么以及如何修复它吗?它似乎只读了一次所有的行,然后就不再读了。。。每次外循环运行时,我都需要内循环逐行读取。
这是我的密码。
private static void getGUIDAndType()
{
try
{
Console.WriteLine("Begin.");
String dbFilePath = @"C:'WindowsApps'CRM'crm_interface'data'";
StreamReader dbsr = new StreamReader(dbFilePath + "newdbcontents.txt");
List<string> dblines = new List<string>();
String newDataPath = @"C:'WindowsApps'CRM'crm_interface'data'";
StreamReader nsr = new StreamReader(newDataPath + "HolidayList1.txt");
List<string> new1 = new List<string>();
string dbline;
string newline;
Program prog = new Program();
while ((dbline = dbsr.ReadLine()) != null)
{
while ((newline = nsr.ReadLine()) != null)
{
newline = newline.Trim();
if (dbline.IndexOf(newline) != -1)
{//if found... get all info for now
Console.WriteLine("FOUND: " + newline);
System.Threading.Thread.Sleep(1000);
new1.Add(newline);
}
else
{//the first line of db does not contain this line...
//go to next newline.
Console.WriteLine("Lines do not match - continuing");
continue;
}
}
nsr.Close();
Console.WriteLine("should be run as many times as there are dblines");
Console.WriteLine(newline);
System.Threading.Thread.Sleep(5000);
//continue;
}
Console.WriteLine("Writing to dbc2.txt");
System.IO.File.WriteAllLines(@"C:'WindowsApps'CRM'crm_interface'data'dbc2.txt", new1.ToArray());
Console.WriteLine("Finished. Press ENTER to continue.");
Console.WriteLine("End.");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex);
Console.ReadLine();
}
}
我尝试将内部循环设置为方法,但当我在方法中引用dbline时,我在这一行得到了对象引用异常:CCD_ 1。并没有花太多时间试图解决这个问题,而是回到了嵌套循环;但如果我采用这种方法,我想我的结果不会有任何不同。
如果你能想出更好的方法来做我正在努力的事情,请告诉我。我不能使用contains,因为我引用的两个txt文档中的行不完全相同。
谢谢。
对于外循环的每次迭代,您需要将内循环的StreamReader
倒带到文件的开头:
while ((dbline = dbsr.ReadLine()) != null)
{
// Reset
nsr.BaseStream.Position = 0;
nsr.DiscardBufferedData();
while ((newline = nsr.ReadLine()) != null)
{
.....
}
nsr.Close(); // remove that
根据评论编辑:
您还需要在内部循环之后移除StreamReader的Close(),在外部循环之后移动它。
您的内部循环会消耗该文件。回到最初。
由于您的while
循环在没有break
或return
语句的情况下终止,这意味着此循环条件评估为false:
(newline = nsr.ReadLine()) != null
也就是说,nsr.Readline()
正在返回null
,因为您已经到达了文件的末尾。
如果你真的打算从nsr
中多次读取行,你可以通过重置底层Stream
上的位置并丢弃if (dbline.IndexOf(newline) != -1)
0的缓冲区来寻找开头:
nsr.BaseStream.Position = 0;
nsr.DiscardBufferedData();