获取文件夹文件目录忽略所选文件夹的顶层

时间:2016-09-07 05:04:01

标签: c#

使用这行代码获取文件夹目录

string[] fileEntries = Directory.GetFiles(@"C:\Users\Desktop\WebApi\", "*",SearchOption.TopDirectoryOnly);

返回

C:\Users\Desktop\WebApi\COPYING.evaluation
C:\Users\Desktop\WebApi\Global.asax
C:\Users\Desktop\WebApi\MobileUserAgent.deploy-readme.txt
C:\Users\Desktop\WebApi\MobileUserAgent.deploy.cmd
C:\Users\Desktop\WebApi\MobileUserAgent.SetParameters.xml
C:\Users\Desktop\WebApi\MobileUserAgent.SourceManifest.xml
C:\Users\Desktop\WebApi\MobileUserAgent.zip
C:\Users\Desktop\WebApi\packages.config
C:\Users\Desktop\WebApi\Web.config

必需

\WebApi\COPYING.evaluation
\WebApi\Global.asax
\WebApi\MobileUserAgent.deploy-readme.txt
\WebApi\MobileUserAgent.deploy.cmd
\WebApi\MobileUserAgent.SetParameters.xml
\WebApi\MobileUserAgent.SourceManifest.xml
\WebApi\MobileUserAgent.zip
\WebApi\packages.config
\WebApi\Web.config

对此的任何建议

2 个答案:

答案 0 :(得分:0)

您只需Substring结果:

string[] fileEntries = Directory.GetFiles(@"C:\Users\Desktop\WebApi\", "*", 
                                            SearchOption.TopDirectoryOnly)
                                .Select(x=> x.Substring( x.IndexOf("\\WebApi"))).ToArray();

答案 1 :(得分:0)

foreach (var s in fileEntries)
{
    Console.WriteLine(Path.GetFileName(Path.GetDirectoryName(s)) + "\\" + Path.GetFileName(s));
}

或者

List<string> lst = fileEntries.Select(s => Path.GetFileName(Path.GetDirectoryName(s)) + "\\" + Path.GetFileName(s)).ToList<string>();

foreach (var item in lst)
{
    Console.WriteLine(item);
}