How to get path from different files in different

2019-09-08 15:52发布

问题:

I need to get path for each file in directories

eg: c:/a/b/c/1.jar and c:/dir/bin/2.jar must be saved as string

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

But the folders name may change in the future and I don't want to write this manually

Thanks for help

EDIT 1: I've got the folder with few folders into. in each folder is files. I need to get all files directory in one string. eg: "dir1; dir2; dir3; ..." but I can give only directory of main folder "c:/bin"

EDIT 2: Solved by Sayse

回答1:

You can use Directory.EnumerateFiles

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

If you wish for all files to be in one long string then you can use

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

If its only directories you want

var allDirs = Directory.EnumerateDirectories("...",
    "*",
     SearchOption.AllDirectories);
var dirString = string.Join(";", allDirs);


回答2:

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 , like "C:\MyProgram1.exe;C:\MyFolder\MyProgram2.exe;C:\MyFolder2\MyProgram2.dll"

myfolder inclueds all folders, like "C:\MyFolder;C:\MyFolder2";