2015-04-23 48 views
-2

這是一個代碼,用於列出目錄中的文件,然後用戶可以輸入文件名來打開文件。C#列出沒有隱藏文件的文件(Plus列表選項)

public static void openFile() 
     { 
      // List files in FormatedDocuments directory 
      String[] showFiles = Directory.GetFiles("FormatedDocuments"); 

      int filesList = showFiles.GetUpperBound (0) + 1; 
      const String folderToOpen = @"FormatedDocuments/"; 

      Console.WriteLine ("Here is the list of files:"); 
      for (int i = 0; i < filesList; i++) { 
       Console.WriteLine ("\tFile : " + Path.GetFileName (showFiles [i])); 
      } 

      // When listing is finished, ask the user to select the file he want to open 
      Console.WriteLine (@"Type the filename (With extension) you want to open:"); 
      String userChoice = folderToOpen + Console.ReadLine(); 
      Process.Start (userChoice); // Loading with default application regarding the file extension 

     } 

我的問題是:

  1. 如何列出所選目錄中唯一可見的文件? [DONE]

  2. 如何在控制檯中返回每個文件之前的數字,並要求用戶鍵入此數字而不是完整的文件名? [等待命題]

我是一個初學者,嘗試通過自己學習,不要在您的解決方案請,我知道我當前的代碼沒有經過優化過的「專家」,我何樂而不爲呢一步一步,但我接受你對此代碼的幫助:)

謝謝你的回答。

回答

2

我發現this

這應該爲你工作:

DirectoryInfo directory = new DirectoryInfo(@"C:\temp"); 
FileInfo[] files = directory.GetFiles(); 

var filtered = files.Select(f => f) 
        .Where(f => (f.Attributes & FileAttributes.Hidden) == 0); 

foreach (var f in filtered) { 
    Debug.WriteLine(f); 
} 
+0

您好,我已經適應這個代碼到我的代碼,但有可能在前面加一個數並輸入這個數字打開指定的文件,而不是輸入完整的文件名?謝謝。 –

+0

當然,你可以簡單地在foreach循環之上和debug.writeline(yourvariablename ++)之後創建一個int,然後在debug.writeline中更改debug.writeline(yourvariablename + f) – Thealon

+0

我嘗試了多個代碼,但我無法使用列出代碼並在列出的每個文件前返回一個數字,並使用此編號調用與該文件關聯的process.start。 –