2013-11-25 21 views
-1

一直在C#文件目錄的東西工作,我想我可能只是忘記了一些簡單的東西。所以讓我說我有4個文件夾,我需要檢查文件夾是否存在,然後顯示文件夾中的文件。但是我堅持的部分是檢查讓我們用四個文件夾中的一個說出文件的創建日期。幾乎就像我錯過了文件夾內文件的路徑實際路徑。這裏是我迄今爲止的代碼。文件和目錄C#

 string end; 
     string directoryName; 
     string fileName; 
     string[] listOfFiles; 

     Console.Write("Enter the name of the folder: "); 
     directoryName = Console.ReadLine(); 
     while (directoryName != "end") 
     { 
      if (Directory.Exists(directoryName)) 
      { 
       Console.WriteLine("Directory exists, and it contains the following:"); 
       listOfFiles = Directory.GetFiles(directoryName); 
       for (int x = 0; x < listOfFiles.Length; ++x) 
        Console.WriteLine(" {0}", listOfFiles[x]); 

      } 

      Console.Write("Enter a filename: "); 
      fileName = Console.ReadLine(); 
      if(File.Exists(fileName)) // Almost like a path needs to be here. 
      { 
       Console.WriteLine("File was created " + File.GetCreationTime(fileName)); 
      } 
     } 

只是想櫃面有人問程序exe文件和文件夾都位於一起

回答

2

你的直覺是正確的。 File.Exists需要一個完整路徑(就像幾乎所有其他Filesystem API一樣)。

添加路徑Path.Combine()。請參見How do I join two paths in C#?

fileName = Console.ReadLine(); 
var filePath = Path.Combine(directoryName, fileName); 
if (File.Exists(filePath)) // Almost like a path needs to be here - Yep! 
+0

全部屬於您的。乾杯。 –