How to get the path from different files in different directories?

I need to get the path for each file in directories

for example: c: /a/b/c/1.jar and c: /dir/bin/2.jar should be saved as a string

"c: /a/b/c/1.jar; c: /dir/bin/2.jar; ..."

But the folder name may change in the future, and I do not want to write it manually

thanks for the help

EDIT 1: I have a folder with several folders. Each folder contains files. I need to get the entire file directory on one line. for example: "dir1; dir2; dir3; ..." but I can only provide the directory of the main folder "c: / bin"

EDIT 2: Solved by Sayse

0
source share
2 answers

You can use Directory.EnumerateFiles

var allFiles = Directory.EnumerateFiles(sourceDirectory, "*.*", //also can use "*.jar" here for just jar files SearchOption.AllDirectories); 

If you want all the files to be on one long line, you can use

 var fileString = string.Join(",", allFiles); 

If its the only directories you want

 var allDirs = Directory.EnumerateDirectories("...", "*", SearchOption.AllDirectories); var dirString = string.Join(";", allDirs); 
+2
source
 class Program { static void Main(string[] args) { DirectoryInfo di = new DirectoryInfo("C:\\"); FullDirList(di, "*"); Console.WriteLine("Done"); Console.Read(); } static string myfolders = "";// Your string, which inclueds the folders like this: "c:/a/b/c; c:/dir/bin;..." static string myfiles = ""; // Your string, which inclueds the file like this: "c:/a/b/c/1.jar; c:/dir/bin/2.jar;..." static List<FileInfo> files = new List<FileInfo>(); // List that will hold the files and subfiles in path static List<DirectoryInfo> folders = new List<DirectoryInfo>(); // List that hold direcotries that cannot be accessed static void FullDirList(DirectoryInfo dir, string searchPattern) { // Console.WriteLine("Directory {0}", dir.FullName); // list the files try { foreach (FileInfo f in dir.GetFiles(searchPattern)) { //Console.WriteLine("File {0}", f.FullName); files.Add(f); myfiles += f.FullName + ";"; } } catch { Console.WriteLine("Directory {0} \n could not be accessed!!!!", dir.FullName); return; // We alredy got an error trying to access dir so dont try to access it again } // process each directory // If I have been able to see the files in the directory I should also be able // to look at its directories so I dont think I should place this in a try catch block foreach (DirectoryInfo d in dir.GetDirectories()) { myfolders += d.FullName + ";"; folders.Add(d); FullDirList(d, searchPattern); } } } 

myfiles includes all files, such as "C: \ MyProgram1.exe; C: \ MyFolder \ MyProgram2.exe; C: \ MyFolder2 \ MyProgram2.dll"

myfolder includes all folders, such as "C: \ MyFolder; C: \ MyFolder2";

+1
source

Source: https://habr.com/ru/post/1491095/


All Articles