2014-12-04 222 views
-1

如何做一个Directory.GetFiles并排除名为“abc”和“xyz”的文件?Directory.GetFiles(strFolderPath)排除某些文件名VB.NET

基本上我有一个DIR,所有文件都存在,一组文件必须发送到一个部门,而“abc”和“xyz”文件需要发送到另一个部门?

目前,我这样做:

'Standard Documents 
Dim strAttachments As List(Of String) = New List(Of String) 
strAttachments.AddRange(Directory.GetFiles(GlobalVariables.strFolderPath)) 

我需要相同的功能,但不包括的文件,然后做如上类似的命令中包含的文件到另一个地址。

干杯,,

詹姆斯

UPDATE

Dim exclude = {"ATS_Declaration"} 
Dim myFiles = From fn In Directory.EnumerateFiles(GlobalVariables.strFolderPath) 
       Where Not exclude.Contains(Path.GetFileNameWithoutExtension(fn), StringComparer.InvariantCultureIgnoreCase) 
Dim strAttachments As List(Of String) = New List(Of String)(myFiles) 
+1

可能重复[从Directory.EnumerateFiles基于多个条件排除文件](http://stackoverflow.com/questions/27285113/exclude-files-from-directory-enumeratefiles-based-on-multiple-criteria) – Plutonix 2014-12-04 15:28:36

+0

为什么不迭代strAttachments并在之后创建两个列表? – WeSt 2014-12-04 15:28:43

回答

2

您可以使用LINQ和System.IO.Path.GetFileNameWithoutExtension

Dim exclude = { "abc", "xyz" } 
Dim myFiles = From fn in Directory.EnumerateFiles(GlobalVariables.strFolderPath) 
       Where Not exclude.Contains(Path.GetFileNameWithoutExtension(fn), StringComparer.InvariantCultureIgnorecase) 
Dim strAttachments As List(Of String) = New List(Of String)(myFiles) 

请注意,我用EnumerateFiles,因为这不需要t先将所有内容加载到内存中。

+0

你好, 我用你的代码,但它仍然包括我的文件“ATS_Declaration”。是否必须限定完整路径以排除它或只是文件名? (包括扩展名) – Lynchie 2014-12-04 15:47:25

+1

@Lynchie:你是否在'string()'中加入了'ATS_Declaration'?你真的使用了上面的代码,在我认为你想排除特定扩展的第一个版本中,因此使用了'Path.GetExtension'。但是现在我正在使用'GetFileNameWithoutExtension'。 – 2014-12-04 15:48:47

+0

Hi Tim, 是的 - 我将把我的更新代码放在主要问题中。 它仍然包含strAttachments列表中的文件。 – Lynchie 2014-12-04 15:50:33