如何从不同目录中的不同文件获取路径

本文关键字:文件 路径 获取 | 更新日期: 2023-09-27 18:21:59

我需要获取目录中每个文件的路径

例如:c:/a/b/c/1.jar和c:/dir/bin/2.jar必须保存为字符串

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

但是文件夹名称可能会在未来更改,我不想手动写这个

感谢的帮助

第1版:我有一个文件夹,里面只有几个文件夹。每个文件夹中都有文件。我需要在一个字符串中获取所有文件的目录。例如:";dir1;dir2;dir3"但我只能给出主文件夹的目录";c:/bin";

编辑2:由Sayse 解决

如何从不同目录中的不同文件获取路径

您可以使用Directory.EnumerateFiles

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

如果你希望所有文件都在一个长字符串中,那么你可以使用

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

如果它的唯一目录你想要

var allDirs = Directory.EnumerateDirectories("...",
    "*",
     SearchOption.AllDirectories);
var dirString = string.Join(";", allDirs);
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包括所有文件,如"C:''MyProgram1.exe;C:''MyFolder''MyProgram2.exe;C:''MySFolder2''MyProgram2.dll"

myfolder包含所有文件夹,如"C:''MyFolder;C:''MyFolder2";