Please look at the following code snippet. I'm getting a nullreferenceexception at "this.directories.Add(new directory(s));". The recursion seems to be working until it "unwinds", at which point "new directory(s)" seems to be a null. I'm not sure why it is behaving this way, I thought perhaps there are special rules because the recursion is in the constructor. Please help.
namespace AnalyzeDir
{
class directory
{
public string[] files;
public ArrayList directories;
public string mypath;
public string myname;
public directory(string mp)
{
mypath = mp;
myname = mypath.Substring(mypath.LastIndexOf("\\"));
files = Directory.GetFiles(mypath);
fillDirectoriesRescursive();
}
public void fillDirectoriesRescursive()
{
string[] dirpaths = Directory.GetDirectories(mypath);
if (dirpaths != null && (dirpaths.Length > 0))
{
foreach(string s in dirpaths)
{
this.directories.Add(new directory(s));
}
}
}
You haven't initialized directories
to be anything.
I'd suggest not doing this in the constructor, but instead moving it to a method call. It goes back to "implied behavior", where you shouldn't have big complicated foreign system logic inside of property accessors.
You are also using a very old construct, ArrayList
. I'd suggest using an ICollection<directory>
instead. More type-safety and all that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With