2017-09-26 57 views
-3

我已閱讀與我的情況相關的stackoverflow問題。 他們不回答基本問題。 我的應用程序允許用戶鍵入完全限定的路徑。該路徑必須是文件。該文件尚不存在(他們正在保存備份)。如果您使用getattributes方法,則會在找不到文件時觸發try/catch的catch。 (因爲它不應該)。我需要捕捉用戶是否放入目錄的路徑,以及路徑是否指向文件不存在的文件。如果發生任何一種情況,我需要向用戶提供定向反饋。我正在使用.NET Framework 4.5.2的C#。確定路徑是文件還是隻是一個目錄 - 當文件還不存在

感謝您的指點。

+0

「嘗試捕捉catch/catch」 - 這是什麼意思?這是一個新功能嗎?您只需確認完整路徑不存在,然後刪除最後一個路徑段並確認它是一個現有目錄。你能找出一個文件是否存在?你能找出目錄是否存在嗎?你能從字符串中刪除路徑段嗎?這些都是微不足道的。 –

+2

下面是確定給定輸入是目錄,文件還是不存在的鏈接: https://msdn.microsoft.com/en-us/library/system.io.directory.exists(v=vs。 110).aspx –

+6

沒有'File.Exists'和'Directory.Exists'方法可以幫助你嗎? – dcg

回答

0

你可以試試這個,看看這是你在找什麼。我假設用戶將輸入文件的擴展名,正如你所提到的,用戶將輸入完全合格的路徑。

static void Main(string[] args) 
    { 
     Console.WriteLine("Enter fully qualified path of the file to be accessed."); 
     var eneteredPath = Console.ReadLine(); 
     var isItFile = Path.HasExtension(eneteredPath); 
     if (isItFile) 
     { 
      Console.WriteLine($"Specified File exists = {File.Exists(eneteredPath)}"); 
     } 
     else if(Directory.Exists(eneteredPath)) 
     { 
      Console.WriteLine($"Specified path is to a directory."); 
     } 
    } 
0

所以我有一個簡單的形式與txtInput,和一個按鈕:

using System.IO; 

private void cmdCheck_Click(object sender, EventArgs e) 
    { 
     if (Directory.Exists(txtInput.Text)) 
     { 
      // This is a directory, not a file. 
     } 
     else 
     { 
      try 
      { 
       if (File.Exists(txtInput.Text)) 
       { 
        var fileInfo = new FileInfo(txtInput.Text); 

        // File exists and now we have the information. Alert the user. 
       } 
       else 
       { 
        // File doesn't exist. Do things. 
       } 
      } 
      catch (Exception ex) 
      { 
       Trace.WriteLine(ex.Message, "ERROR"); 
      } 
     } 
    } 

這是否符合您的要求嗎?

+0

blaze_125提出了一個不需要擴展名的文件的好處,所以我修改了我的答案。 – Ratatoskr

2

對於文件來說,文件擴展名不是強制性的,因爲它是一個有效的文件。因此,您不能依賴具有文件擴展名的路徑將其稱爲文件。

using System; 

namespace FileFolder_46434099 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string incomingpath = @"C:\temp\3075"; 
      if (System.IO.Directory.Exists(incomingpath)) 
      { 
       Console.WriteLine("path is a directory"); 
      } 
      else if (System.IO.File.Exists(incomingpath)) 
      { 
       Console.WriteLine("path is of a file"); 
      } 
      Console.ReadLine(); 
     } 
    } 
} 

在這種情況下... C:\temp\3075實際上是一個文件,程序返回它是這樣。

0

這將幫助您https://www.dotnetperls.com/path

路徑。這條道路通向某處。它在樹木和建築物之間。雲移動。陽光照射到地面,我們的方向很清晰。 使用Path,.NET Framework中的類,我們有內置方法。這個類有助於處理文件路徑。它是System.IO的一部分。

相關問題