I want to list every file and directory contained in a directory and subdirectories of that directory. If I chose C:\\ as the directory, the program would get every name of
A littlebit simple and slowly but working!! if you do not give a filepath basicly use the "fixPath" this is just example.... you can search the correct fileType what you want, i did a mistake when i chosen the list name because the "temporaryFileList is the searched file list so carry on that.... and the "errorList" is speaks for itself
static public void Search(string path, string fileType, List<string> temporaryFileList, List<string> errorList)
{
List<string> temporaryDirectories = new List<string>();
//string fix = @"C:\Users\" + Environment.UserName + @"\";
string fix = @"C:\";
string folders = "";
//Alap útvonal megadása
if (path.Length != 0)
{ folders = path; }
else { path = fix; }
int j = 0;
int equals = 0;
bool end = true;
do
{
equals = j;
int k = 0;
try
{
int foldersNumber =
Directory.GetDirectories(folders).Count();
int fileNumber = Directory.GetFiles(folders).Count();
if ((foldersNumber != 0 || fileNumber != 0) && equals == j)
{
for (int i = k; k <
Directory.GetDirectories(folders).Length;)
{
temporaryDirectories.Add(Directory.GetDirectories(folders)[k]);
k++;
}
if (temporaryDirectories.Count == j)
{
end = false;
break;
}
foreach (string files in Directory.GetFiles(folders))
{
if (files != string.Empty)
{
if (fileType.Length == 0)
{
temporaryDirectories.Add(files);
}
else
{
if (files.Contains(fileType))
{
temporaryDirectories.Add(files);
}
}
}
else
{
break;
}
}
}
equals++;
for (int i = j; i < temporaryDirectories.Count;)
{
folders = temporaryDirectories[i];
j++;
break;
}
}
catch (Exception ex)
{
errorList.Add(folders);
for (int i = j; i < temporaryDirectories.Count;)
{
folders = temporaryDirectories[i];
j++;
break;
}
}
} while (end);
}
Directory.GetFileSystemEntries exists in .NET 4.0+ and returns both files and directories. Call it like so:
string[] entries = Directory.GetFileSystemEntries(path, "*", SearchOption.AllDirectories);
Note that it won't cope with attempts to list the contents of subdirectories that you don't have access to (UnauthorizedAccessException), but it may be sufficient for your needs.
using System.IO;
using System.Text;
string[] filePaths = Directory.GetFiles(@"path", "*.*", SearchOption.AllDirectories);
I use the following code with a form that has 2 buttons, one for exit and the other to start. A folder browser dialog and a save file dialog. Code is listed below and works on my system Windows10 (64):
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Directory_List
{
public partial class Form1 : Form
{
public string MyPath = "";
public string MyFileName = "";
public string str = "";
public Form1()
{
InitializeComponent();
}
private void cmdQuit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void cmdGetDirectory_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
MyPath = folderBrowserDialog1.SelectedPath;
saveFileDialog1.ShowDialog();
MyFileName = saveFileDialog1.FileName;
str = "Folder = " + MyPath + "\r\n\r\n\r\n";
DirectorySearch(MyPath);
var result = MessageBox.Show("Directory saved to Disk!", "", MessageBoxButtons.OK);
Application.Exit();
}
public void DirectorySearch(string dir)
{
try
{
foreach (string f in Directory.GetFiles(dir))
{
str = str + dir + "\\" + (Path.GetFileName(f)) + "\r\n";
}
foreach (string d in Directory.GetDirectories(dir, "*"))
{
DirectorySearch(d);
}
System.IO.File.WriteAllText(MyFileName, str);
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Some improved version with max lvl to go down in directory and option to exclude folders:
using System;
using System.IO;
class MainClass {
public static void Main (string[] args) {
var dir = @"C:\directory\to\print";
PrintDirectoryTree(dir, 2, new string[] {"folder3"});
}
public static void PrintDirectoryTree(string directory, int lvl, string[] excludedFolders = null, string lvlSeperator = "")
{
excludedFolders = excludedFolders ?? new string[0];
foreach (string f in Directory.GetFiles(directory))
{
Console.WriteLine(lvlSeperator+Path.GetFileName(f));
}
foreach (string d in Directory.GetDirectories(directory))
{
Console.WriteLine(lvlSeperator + "-" + Path.GetFileName(d));
if(lvl > 0 && Array.IndexOf(excludedFolders, Path.GetFileName(d)) < 0)
{
PrintDirectoryTree(d, lvl-1, excludedFolders, lvlSeperator+" ");
}
}
}
}
input directory:
-folder1
file1.txt
-folder2
file2.txt
-folder5
file6.txt
-folder3
file3.txt
-folder4
file4.txt
file5.txt
output of the function (content of folder5 is excluded due to lvl limit and content of folder3 is excluded because it is in excludedFolders array):
-folder1
file1.txt
-folder2
file2.txt
-folder5
-folder3
-folder4
file4.txt
file5.txt
I am afraid, the GetFiles
method returns list of files but not the directories. The list in the question prompts me that the result should include the folders as well. If you want more customized list, you may try calling GetFiles
and GetDirectories
recursively. Try this:
List<string> AllFiles = new List<string>();
void ParsePath(string path)
{
string[] SubDirs = Directory.GetDirectories(path);
AllFiles.AddRange(SubDirs);
AllFiles.AddRange(Directory.GetFiles(path));
foreach (string subdir in SubDirs)
ParsePath(subdir);
}
Tip: You can use FileInfo
and DirectoryInfo
classes if you need to check any specific attribute.