[英]How can I return a directories files/folders without the directory path included?
I am trying to extract a list of files within a folder and am currently using: 我正在尝试提取文件夹中的文件列表,目前正在使用:
string[] files = Directory.GetFiles(txtbxNewFolder.Text);
But that returns things like "C:\\Users\\Dahlia\\Desktop\\New Folder\\jerry.txt". 但这会返回“C:\\ Users \\ Dahlia \\ Desktop \\ New Folder \\ jerry.txt”之类的内容。 Is there a way to return only "jerry.txt", or do I need to do some sort of split on the array strings?
有没有办法只返回“jerry.txt”,还是我需要对数组字符串进行某种拆分?
I am also trying to return a list of folders within a directory and am currently using: 我还试图返回目录中的文件夹列表,目前正在使用:
string[] folders = Directory.GetDirectories(txtbxOldFolder.Text);
But that returns things like "C:\\Users\\Dahlia\\Desktop\\New Folder\\folder1". 但这会返回“C:\\ Users \\ Dahlia \\ Desktop \\ New Folder \\ folder1”之类的内容。 Is there a way to return only "folder1", or do I need to do some sort of split on the array strings?
有没有办法只返回“folder1”,还是我需要对数组字符串进行某种拆分?
Using LINQ you can get a list of just the files: 使用LINQ,您可以获得仅包含文件的列表:
Directory.GetFiles(txtbxNewFolder.Text).Select(f => Path.GetFileName(f));
Though rather than GetFiles
I'd probably use: 虽然不是
GetFiles
我可能会使用:
Directory.EnumerateFiles(txtbxNewFolder.Text).Select(f => Path.GetFileName(f));
It isn't as simple to get the directory name, but this should work (untested): 获取目录名称并不是那么简单,但这应该有效(未经测试):
Directory.GetDirectories(txtbxOldFolder.Text)
.Select(d => new DirectoryInfo(d).Name);
Similarly, there is a: 同样,有一个:
Directory.EnumerateDirectories(txtbxOldFolder.Text)
.Select(d => new DirectoryInfo(d).Name);
You could use Path.GetFileName and LINQ 您可以使用Path.GetFileName和LINQ
eg: 例如:
string[] files = Directory.GetFiles(txtbxNewFolder.Text)
.Select(f => Path.GetFileName(s))
.ToArray();
Have a look at the FileInfo and DirectoryInfo classes. 看看FileInfo和DirectoryInfo类。
You can do: 你可以做:
foreach (String file in files) {
var fi = new FileInfo(file);
Console.Out.WriteLine(fi.Name);
}
Similar for DirectoryInfo. 与DirectoryInfo类似。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.