我有一个搜索文件夹的递归函数
private int contFiles = 0;
private List<string> GetFiles(string folder, string filter)
{
var files = new List<string>();
Action<string> getFilesInDir = null;
getFilesInDir = new Action<string>(dir =>
{
contFiles++;
tslQuant.Text = contFiles.ToString(); //ToolStripItem
try
{
// get all the files in this directory
files.AddRange(Directory.GetFiles(dir, filter));
// and recursively visit the directories
foreach (var subdir in Directory.GetDirectories(dir))
{
getFilesInDir(subdir);
}
}
catch (UnauthorizedAccessException uae)
{
Console.WriteLine(uae.Message);
}
});
getFilesInDir(folder);
return files;
}
函数增加contFiles并将该数字设置为ToolStripItem,但我总是得到"System.ArgumentOutOfRangeException"。
我如何增加这个值(最多5000)并在TSI中显示?
错误:系统。未处理ArgumentOutOfRangeExceptionMessage="索引超出范围。"它必须是非负的,并且小于集合的大小。参数名称:index"
源= " mscorlib "ParamName = "指数"加:在System.Collections.ArrayList。get_Item (Int32指数)在System.Windows.Forms.ToolStripItemCollection。get_Item (Int32指数)在System.Windows.Forms.ToolStrip。OnPaint (PaintEventArgs e)在System.Windows.Forms.Control。PaintWithErrorHandling(PaintEventArgs, Int16层)在System.Windows.Forms.Control.WmPaint (Message&米)在System.Windows.Forms.Control.WndProc (Message&米)在System.Windows.Forms.ToolStrip.WndProc (Message&米)在System.Windows.Forms.StatusStrip.WndProc (Message&米)在System.Windows.Forms.Control.ControlNativeWindow.WndProc (Message&米)在System.Windows.Forms.NativeWindow。DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)InnerException:
编辑
在阅读了整个程序的代码之后,我注意到这个函数是在Do_Work中被调用的,所以我使用了backgroundWorker2.ReportProgress((1));
报告,一切正常。
我不知道为什么,但不知何故,toolStripItem甚至可以在backgroundWorker中访问,标签和其他控件不能
似乎您从未将contFiles
变量重置为零。如果你多次调用GetFiles()
,你可能会遇到问题。所以你可以在这里把它重置为0
contFiles = 0; // Reset variable to prevent overflow
var files = new List<string>();
Action<string> getFilesInDir = null;
getFilesInDir = new Action<string>(dir =>
{ ...