2014-12-04 223 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