我需要为目录
中的每个文件获取路径例如: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解决
答案 0 :(得分:2)
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);
答案 1 :(得分:1)
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:\ MyFolder2 \ MyProgram2.dll”
myfolder
包含所有文件夹,例如“C:\ MyFolder; C:\ MyFolder2”;