2011-10-25 45 views

回答

4

Path類還爲您提供了很多不錯的方法和屬性,例如GetFullPath()。所有細節見MSDN

0

使用DirectoryInfo類指向目錄的路徑。與FileInfo在很大程度上相同的問題。

請注意,該路徑的屬性稱爲FullName。

DirectoryInfo di = new DirectoryInfo(@"C:\Foo\Bar\"); 
string path = di.FullName; 

如果要確定路徑是否是一個文件或目錄,你可以使用來自Path類的靜態方法:

string path1 = @"C:\Foo\Bar.docx"; 
string path2 = @"C:\Foo\"; 

bool output1 = Path.HasExtension(path1); //Returns true 
bool output2 = Path.HasExtension(path2); //Returns false 

然而,路徑也可能包含一些可能類似於一個擴展名,所以你可能想與其他一些檢查一起使用它,例如bool isFile = File.Exists(path);

+0

如果它是一個文件,而不是目錄呢? –

+0

您確實需要區分何時需要目錄路徑或何時需要文件路徑。據我所知,沒有通用的「路徑」類來表示文件或目錄。 –

+0

原來我錯了 - 看看我編輯的答案。 –

0

我覺得it's-

DirectoryInfo.FullName 
+0

如果它是一個文件,而不是目錄? –

0

試試這個:

String strYourFullPath = ""; 
IO.Path.GetDirectoryName(strYourFullPath) 
+0

它沒有返回完整路徑 –

+0

它的確如此。當strYourFullPath是一個文件時,它返回它所在的目錄,當它的strYourFullPath是一個目錄時,它保持不變。如果這不是你正在尋找的東西,那麼你想要達到什麼目的? –

0

使用DirectoryInfo類延伸FileSystemInfo,將給予正確的結果對於任何一個文件或目錄。

 string path = @"c:\somefileOrDirectory"; 
     var directoryInfo = new DirectoryInfo(path); 
     var fullPath = directoryInfo.FullName; 
0

msdnFileSystemInfo.FullName得到目錄的完整路徑或文件,並can be appliedFileInfo

FileInfo fi1 = new FileInfo(@"C:\someFile.txt"); 
Debug.WriteLine(fi1.FullName); // Will produce C:\someFile.txt 
FileInfo fi2 = new FileInfo(@"C:\SomeDirectory\"); 
Debug.WriteLine(fi2.FullName); // Will produce C:\SomeDirectory\ 
+0

FileSystemInfo是一個抽象類,我不能做新的FileSystemInfo(路徑).FullPath –

+0

@LouisRhys:你嘗試過'FileInfo(path).FullName'嗎? – Otiel

+1

@LouisRhys - 爲什麼你需要準確地擁有** FileSystemInfo **變量? ** FullPath **或** FullName **返回一個** String **。 **新的FileSystemInfo(路徑).FullPath **沒有任何意義 –