我之前发过一个问题,在这里: C# Array of List Index out of bounds 它的代码大致相同。我的代码工作正常但是当它完成一个文件时,而不是突破到下一个文件名(在foreach循环中)它保持相同 - 这种方式匹配总是重复,他只是在不同的列表位置添加相同的东西。我试过改变fs.Close()的位置,添加一个break语句但没有一个工作。
在那种情况下我做错了什么?在我的逻辑视图中,它应该在完成特定文件后转到外部循环。
我将代码编辑为最小的需求 - 无论如何,这里是完整代码的链接: http://pastebin.com/xcKczQLC
这个与整个代码的链接包含我打开文件的部分。
感谢。
foreach (string fileName in fullFileName) //Start processing each file
{
// Lots of code here - reading a mixed file - no need to show
bool b = filecontents.Contains("CIP3EndOfFile");
if(b)
{
//Code manipulating contents in filecontents (a string)
var matches = Regex.Matches(query, pattern);
//When the foreach (Match m in matches) loop ends he always returns to the line above
finalcontent[listpos] = new List<xmldata>();//Initializing a list for each filename
foreach (Match m in matches)
{
//Lots of code doing some operations with the found match
if (i < colors_str.Length)
{
finalcontent[listpos].Add(new xmldata//The exception is thrown right here
{
colorname = colors_str[i],
colorvalues = values,
});//Closing list add declaration
}//Closing if
i++;
}//Closing foreach loop
if (i >= colors_str.Length)
{
listpos++;
i = 0;
}
fs.Close();//closing current file
//In this moment i expected that it would go for the foreach (string fileName in fullFileName) loop
//Instead he returns to this inner foreach loop
}//Closing boolean if
}//End file reading - closing for
}//Finished processing each filename (string filename in filename)
答案 0 :(得分:1)
您无法在此处看到它,但在您的pastebin中,您有一个名为filename
的字段和一个名为fileName
的本地变量,您可以互换使用它们。你真的需要一个好的整理,考虑你如何命名变量,并将这些东西分解成小问题,以便能够调试它。
答案 1 :(得分:0)
也许这是你的问题:
变化:
fs.Close();//closing current file
//In this moment i expected that it would go for the foreach (string fileName in fullFileName) loop
//Instead he returns to this inner foreach loop
}//Closing boolean if
要
//In this moment i expected that it would go for the foreach (string fileName in fullFileName) loop
//Instead he returns to this inner foreach loop
}//Closing boolean if
fs.Close();//closing current file
修改强>
使用using
可以让您编码更安全,它会在您退出循环时自动关闭您的文件:
foreach (string fileName in fullFileName) //Start processing each file
{
using (var fs =new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
}
}