Hello...
I have an application that simply loops through all files in a given path and reports the number back on the form in a label.
I created a application that only does this function and here is the code...
//Form Code...
public partial class Form1 : Form
{
public int iFilesFound = 0;
public Form1()
{
InitializeComponent();
}
public void UpdateFileCounterLabel(int iCtr)
{
//I get the error on any of these lines....
this.iFilesFound = iCtr;
this.lblFileCtr.Text = "| " + Convert.ToString(iFilesFound) + " File(s) Found |";
Application.DoEvents();
}
private void button1_Click(object sender, EventArgs e)
{
clsLoop.GetFileCount();
MessageBox.Show("Done");
}
}
//Seperate Class...
class clsLoop
{
public static int i = 0;
public static void GetFileCount()
{
string[] strFolders = System.IO.Directory.GetDirectories(@"C:\");
string[] strFiles = System.IO.Directory.GetFiles(@"C:\");
foreach (string strFile in strFiles)
{
i++;
Form1 f = (Form1)Application.OpenForms["Form1"];
f.UpdateFileCounterLabel(i);
}
foreach (string strFolder in strFolders)
{
FileAttributes attributes = File.GetAttributes(strFolder);
if ((attributes & FileAttributes.Hidden) != FileAttributes.Hidden)
{
GetFileCount();
}
}
}
}
I have been unable to catch this exception and from what I read I cannot catch it. It appears to crash around 85,000 files found. (This is just a small part of a bigger application where I need to know how many files are in the selected directory so I can calculate processing time and percetage completed).
Thanks For All Your Help In Advance...
Chad
Loading
AlanPosted Apr 13, 2008, 6:43 AM
I think the problem here, Chad, is that each time you make the recursive call to GetFileCount(), the folder to be examined is reset to the root @"C:\" rather than the current folder! This is setting up an infinite sequence which eventually overflows the stack. You therefore need to introduce a parameter for this method so that you can set the starting folder to the current folder for the next recursion.
Also, there is no need to count the individual files in each folder when you can simply use the Length property of the array instead.
Try this version of the clsLoop class which incorporates these points:
class clsLoop
{
public static int i = 0;
public static void GetFileCount(string strStartFolder)
{
Form1 f = (Form1)Application.OpenForms["Form1"];
string[] strFolders = System.IO.Directory.GetDirectories(strStartFolder);
string[] strFiles = System.IO.Directory.GetFiles(strStartFolder);
i += strFiles.Length;
f.UpdateFileCounterLabel(i);
foreach (string strFolder in strFolders)
{
FileAttributes attributes = File.GetAttributes(strFolder);
if ((attributes & FileAttributes.Hidden) != FileAttributes.Hidden)
{
GetFileCount(strFolder);
}
}
}
}
You can then start the ball rolling with:
string strFolder = @"c:\"; // or whatever
clsLoop.i = 0;
clsLoop.GetFileCount(strFolder);