List existing folders / subfolders and folders in a specific root folder

1

Is it possible via code to list the existing folders / files in a specific folder?

Example

And play this list on a grid / table on the WEB for the user to know if the folder he wants to create already exists?

    
asked by anonymous 03.05.2018 / 15:18

1 answer

3

Yes, it is possible, but it is not recommended. You can simply test if it already exists and pass this return to the user.

Another common practice is you use guids to create the folders and save your nickname in the bank. So all users could have their folder called "Test".

To list you can from this code:

string caminho = @"C:\Raiz\";
foreach (string item in Directory.GetDirectories(caminho))
{
    Console.WriteLine(item.Remove(0, caminho.Length));
}

To check if the directory does not exist you should first consult, because the Directory.CreateDirectory() method will only fail if the path is invalid or there are any security constraints. If it already exists it just ignores the statement.

string raiz = @"C:\Raiz\";
string novoDir = "IR";
string mensagem = string.Empty;


if (!Directory.Exists(raiz + novoDir))
{
    Directory.CreateDirectory(raiz + novoDir);
    mensagem = string.Format("O diretório \"{0}\" foi criado com sucesso!", novoDir);
}
else
{
    mensagem = string.Format("O diretório \"{0}\" já existe, escolha um novo nome!", novoDir);
}

Console.WriteLine(mensagem);
    
03.05.2018 / 15:38