当我使用下面的代码行时,我得到一个包含各个文件的整个路径的字符串数组。
private string[] pdfFiles = Directory.GetFiles("C:\\Documents", "*.pdf");
我想知道是否有一种方法可以只检索字符串中的文件名而不是整个路径。
您可以使用Path.GetFileName http://msdn.microsoft.com/en-us/library/system.io.path.getfilename.aspx从完整路径获取文件名
private string[] pdfFiles = Directory.GetFiles("C:\\Documents", "*.pdf")
.Select(Path.GetFileName)
.ToArray();
编辑:上面的解决方案使用LINQ http://en.wikipedia.org/wiki/Linq,所以它至少需要.NET 3.5。这是适用于早期版本的解决方案:
private string[] pdfFiles = GetFileNames("C:\\Documents", "*.pdf");
private static string[] GetFileNames(string path, string filter)
{
string[] files = Directory.GetFiles(path, filter);
for(int i = 0; i < files.Length; i++)
files[i] = Path.GetFileName(files[i]);
return files;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)