2016-04-06 141 views
-5

我需要從服務器路徑中獲取所有帶前綴009的文件。 但我的代碼檢索與0000前綴的所有文件沒有具體與009如何從C#目錄獲取文件

例如開始,我的文件「000028447_ ghf.doc」,「0000316647 abcf.doc」,「009028447_ test2.doc」,「ABCD .DOC」。

string [] files =Directory.GetFiles(filePath,"009*.doc) 

給我所有的文件,除了「abcd.doc」。但是我需要「009028447_ test2.doc」。 如果即時通訊Directory.GetFiles(filePath,「ab * .doc)它將檢索」abcd.doc「,並工作得很好。但當我試圖給像」009「或」00002「模式它不會工作。預計

+2

是你**確定**你正在使用009 * .doc獲取所有文件?我會認真仔細檢查這個斷言與一個小測試程序... –

+0

請重新格式化您的問題,並顯示更多的代碼。 – Alexander

+0

[C#目錄可能有重複。GetFiles與掩碼](http://stackoverflow.com/questions/16664756/c-sharp-directory-getfiles-with-mask) – Set

回答

0

您的代碼段中缺少模式的結束引號字符的代碼應該是:。

string[] files = Directory.GetFiles(filePath, "009*.doc"); 

除此之外,它似乎是工作按預期我已經測試了這個用問題中提到的文件創建一個文件夾:

Contents of testfolder

接下來我創建了一個控制檯應用程序,它使用您的代碼來查找文件,並將所有結果打印到控制檯。輸出是預期的結果:

C:\ testfolder \ 009028447_ test2.doc

下面是控制檯應用程序的全部代碼:

using System; 
using System.IO; 

class Program 
{ 
    static void Main(string[] args) 
    { 
     string filePath = @"C:\testfolder"; 
     string[] files = Directory.GetFiles(filePath, "009*.doc"); 

     // Creates a string with all the elements of the array, separated by ", " 
     string matchingFiles = string.Join(", ", files); 

     Console.WriteLine(matchingFiles); 
     // Since there is only one matching file, the above line only prints: 
     // C:\testfolder\009028447_ test2.doc 
    } 
} 

最後,代碼作品。如果您正在獲得其他結果,那麼您的設置或代碼中必須存在其他與您沒有提及的區別。

+0

謝謝拉爾斯...它不是關於代碼。一些環境問題。一旦我想出來,很快就會更新。 –

-1

如果(我沒有檢查,),這是事實,你只是接受了錯誤的文件,你也許應該使用foreach或LINQ來檢查文件是否符合您的條件:

的foreach:

List<string> arrPaths = new List<string>(); 
Foreach(string strPath in Directory.GetFiles(filePath,".doc")) 
{ 
if(strPath.EndsWith(".doc") & strPath.StartsWith("009")) 
arrPaths.Add(strPath); 
} 

的Linq:

List<string> arrPaths = Directory.GetFiles(filePath,".doc").Where(pths => pths.StartsWith("009") && pths.EndsWith(".doc")).ToList(); 

這兩種方法都不止一個真正的解決方案要解決此問題,但我希望他們幫助:)

編輯

如果你想只得到文件名,我會從你的strPath中減去文件路徑是這樣的:

的foreach:

arrPaths.Add(strPath.Replace(filePath + "\\", "")); 

的Linq:

List<string> arrPaths = Directory.GetFiles(filePath,".doc").Where(pt => pt.StartsWith("009") && pths.EndsWith(".doc")).Select(pths => pths.ToString().Replace(filePath + "\\", "").ToList(); 
+0

檢查是否有任何匹配文件的好方法。但是,請注意'Directory.GetFiles'返回文件的完整路徑,因此該字符串的內容類似於'C:\ myfolder \ 009_example.doc'。 –

+0

好的加法@LarsKristensen,因此我會建議從strPath中減去filePath。編輯它在:) –

+0

@KonstantinJahnel做lambda選擇原因布爾列表鑄造問題? –