2010-09-30 108 views
140

有沒有內建System.IO.Path的東西給我只是文件路徑?從包含文件名的路徑獲取沒有文件名的完整路徑

舉例來說,如果我有一個string

@ 「C:\網絡服務器\ PUBLIC \ myCompany的\ CONFIGS \ promo.xml」,

是有,這將使任何BCL方法我

「c:\ webserver \ public \ myCompany \ configs \」?

+5

可能重複http://stackoverflow.com/questions/674479/how-do-i-get-the-目錄從一個文件完整路徑) – bluish 2014-02-06 16:26:32

+0

FWIW:我已經「放棄了」路徑的「路徑」處理,我們使用我們自己的方法與UNC更好的期望和一致性(嘗試使用GetDirectoryName UNC路徑)和慣例(例如尾隨/)。 – user2864740 2018-02-09 03:59:29

回答

175

Path.GetDirectoryName() ...但您需要知道您傳遞給它的路徑確實包含文件名;它只是從路徑中刪除最後一位,不管它是文件名還是目錄名(它實際上不知道它是哪一個)。

你可以先驗證通過測試的路徑上File.Exists()和/或Directory.Exists()先來看看,如果你需要調用Path.GetDirectoryName

+2

沒有必要調用'File.Exists()'。事實上,如果您找到目錄名稱的原因是創建目錄名稱(如果它尚不存在),那麼它會起到相反的作用。 – 2010-09-30 00:12:05

+2

他的示例明確指出了具有文件名的路徑。如果這是他正在測試的路徑模式,並且如果這些路徑代表現有文件,那麼檢查File.Exists()肯定會有用,您會不同意嗎?因爲情況可能是其他情況,當然,我只是建議他'可以'在文件和/或目錄上使用Exists方法;顯然,適合他的情況。 – 2010-09-30 00:17:26

+0

是的,一個文件名的路徑。沒有什麼可以指示文件存在,因爲文件名稱首先出現。 – 2010-09-30 02:55:01

53
Console.WriteLine(Path.GetDirectoryName(@"C:\hello\my\dear\world.hm")); 
+0

這是最好的。請記住'使用System.IO;'來利用路徑方法 – 2017-12-22 10:41:41

45

Path.GetDirectoryName()返回目錄名,所以你想要的東西(與後反轉固體字符),你可以撥打Path.GetDirectoryName(filePath) + Path.DirectorySeparatorChar

+6

+1 Path.DirectorySeparatorChar很有幫助 – mack 2013-03-28 19:05:28

4

我用這個和它工作得很好:

string[] filePaths = Directory.GetFiles(Path.GetDirectoryName(dialog.FileName)); 

foreach (string file in filePaths) 
{ 
    if (comboBox1.SelectedItem.ToString() == "") 
    { 
     if (file.Contains("c")) 
     { 
      comboBox2.Items.Add(Path.GetFileName(file)); 
     } 
    } 
} 
4

使用 '的getParent()',如圖,很好地工作。 根據需要添加錯誤檢查。

var fn = openFileDialogSapTable.FileName; 
var currentPath = Path.GetFullPath(fn); 
currentPath = Directory.GetParent(currentPath).FullName; 
0
string fileAndPath = @"c:\webserver\public\myCompany\configs\promo.xml"; 

    string currentDirectory = Path.GetDirectoryName(fileAndPath); 

    string fullPathOnly = Path.GetFullPath(currentDirectory); 
的[我如何從一個文件的完整路徑的目錄?(
+2

請提供一些關於上述代碼如何回答問題以改進此答案的信息。 – 2018-02-06 17:40:53