Open sub directories with explorer in C #

4

I am making an application whose purpose is to search and open a sub directory within a folder that is on a server. But what I can do so far is just browse and open the folders that are in the root ...

My code looks like this:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
         public Form1()
         {
                 InitializeComponent();
         }
         private void textBox1_TextChanged(object sender, EventArgs e)
         {
         }
         private void button1_Click(object sender, EventArgs e)
         {
                 string filepath = string.Format("C:\TESTE\{0}", textBox1.Text, SearchOption.AllDirectories);
                 System.Diagnostics.Process prc = new System.Diagnostics.Process();
                 prc.StartInfo.FileName = filepath;
                 prc.Start();
         }

}
}

I know I have to use a recursive function to go through all the folders but I am not able to fit the function into what I mean: the user inserts into the textbox the folder to be searched for, clicks the browse and open button and, if it exists, it opens with explorer this folder:

public void GetSubDirectories()
{
string root = @"C:\teste";

string[] subdirectoryEntries = Directory.GetDirectories(root);

foreach (string subdirectory in subdirectoryEntries)
         LoadSubDirs(subdirectory);
}
private void LoadSubDirs(string dir)
{
Console.WriteLine(dir);
string[] subdirectoryEntries = Directory.GetDirectories(dir);
foreach (string subdirectory in subdirectoryEntries)
{
         LoadSubDirs(subdirectory);
}
}
    
asked by anonymous 20.04.2015 / 00:35

2 answers

1

To traverse all subdirectories recursively use the following method:

static void DirSearch(string sDir)
   {
       try
       {
           foreach (string d in Directory.GetDirectories(sDir))
           {
               foreach (string f in Directory.GetFiles(d))
               {
                   Console.WriteLine(f);
               }
               DirSearch(d);
           }
       }
       catch (System.Exception excpt)
       {
           Console.WriteLine(excpt.Message);
       }
   }

Reference: link

    
20.04.2015 / 18:03
0

If you need to find all directories and your children you can use the Directory.GetDirectories (...) :

string pastaInicial = "C:\teste";
string pastaAEncontrar = "aMinhaPasta";
string[] listaDePastas = Directory.GetDirectories(pastaInicial, pastaAEncontrar, SearchOption.AllDirectories);
// pode verificar se há uma só pasta, se há varias pastas, se não há pastas

The SearchOption.AllDirectories option causes GetDirectories(...) to look for the folder it finds in the home folder and its descendants.

    
30.07.2015 / 13:32