José Perez
asked on
C# Get files, folders and subfolders path
Hi,
I am trying to develop a little app that retrieves all the files, folders and subfolders for an specific directory, but It is only doing it for the main folder, not subfolders.
Can someone please check what I am doing wrong?
Thanks.
I am trying to develop a little app that retrieves all the files, folders and subfolders for an specific directory, but It is only doing it for the main folder, not subfolders.
Can someone please check what I am doing wrong?
Thanks.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace listaEstructura
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnListar_Click(object sender, EventArgs e)
{
GetFiles();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void GetFiles()
{
List<String> Myfiles = new List<string>();
string[] allFiles = System.IO.Directory.GetFiles(txtRuta.Text, "*.*");
if (allFiles.Length > 0)
{
try
{
foreach (string filename in allFiles)
{
this.richTextBox1.Text = string.Join(Environment.NewLine, allFiles);
}
}
catch (SystemException excpt)
{
this.richTextBox1.Text = excpt.Message;
}
}
}
private void btnDir_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
txtRuta.Text = folderBrowserDialog1.SelectedPath;
}
}
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
btw is there someway to cancel it? :(
Hi José Perez,
Please add "SearchOption.AllDirectorie s" in your code. Please check the below code.
string[] allFiles = System.IO.Directory.GetFil es(txtRuta .Text, "*.*", SearchOption.AllDirectorie s);
Regards,
Tapan Pattaniak
Please add "SearchOption.AllDirectorie
string[] allFiles = System.IO.Directory.GetFil
Regards,
Tapan Pattaniak
btw is there someway to cancel it?With that option, no. But you can switch to Directory.EnumerateFiles and be able to do such.
e.g.
private void GetFiles()
{
List<String> Myfiles = new List<string>();
IEnumerable[] allFiles = System.IO.Directory.EnumerateFiles(txtRuta.Text, "*.*", System.IO.SearchOption.AllDirectories);
try
{
foreach (string filename in allFiles)
{
this.richTextBox1.Text = string.Join(Environment.NewLine, allFiles);
if (someCondition)
{
break;
}
}
}
catch (SystemException excpt)
{
this.richTextBox1.Text = excpt.Message;
}
}
ASKER
It displays an error "Can not convert System.Collections.Generic .IEnumerab le<string> into IEnumerable[]" :(
My fault: I changed the type incorrectly. Corrected:
IEnumerable<string> allFiles = System.IO.Directory.EnumerateFiles(txtRuta.Text, "*.*", System.IO.SearchOption.AllDirectories);
ASKER
Thanks a lot for your quick answer!