我得到的最接近的是使用new FileInfo(path).FullPath
,但據我所知FileInfo僅用於文件,而不是目錄。如何使用C#獲取給定路徑的完整路徑(可以是目錄或文件,甚至是完整路徑)?
另請參閱我的意見Jon Skeet's answer here的上下文。
我得到的最接近的是使用new FileInfo(path).FullPath
,但據我所知FileInfo僅用於文件,而不是目錄。如何使用C#獲取給定路徑的完整路徑(可以是目錄或文件,甚至是完整路徑)?
另請參閱我的意見Jon Skeet's answer here的上下文。
Path類還爲您提供了很多不錯的方法和屬性,例如GetFullPath()。所有細節見MSDN。
使用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);
如果它是一個文件,而不是目錄呢? –
您確實需要區分何時需要目錄路徑或何時需要文件路徑。據我所知,沒有通用的「路徑」類來表示文件或目錄。 –
原來我錯了 - 看看我編輯的答案。 –
您可以使用file.getdirectory來完成此操作。
我覺得it's-
DirectoryInfo.FullName
如果它是一個文件,而不是目錄? –
試試這個:
String strYourFullPath = "";
IO.Path.GetDirectoryName(strYourFullPath)
它沒有返回完整路徑 –
它的確如此。當strYourFullPath是一個文件時,它返回它所在的目錄,當它的strYourFullPath是一個目錄時,它保持不變。如果這不是你正在尋找的東西,那麼你想要達到什麼目的? –
使用DirectoryInfo
類延伸FileSystemInfo
,將給予正確的結果對於任何一個文件或目錄。
string path = @"c:\somefileOrDirectory";
var directoryInfo = new DirectoryInfo(path);
var fullPath = directoryInfo.FullName;
據msdn,FileSystemInfo.FullName
得到目錄的完整路徑或文件,並can be applied到FileInfo
。
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\
FileSystemInfo是一個抽象類,我不能做新的FileSystemInfo(路徑).FullPath –
@LouisRhys:你嘗試過'FileInfo(path).FullName'嗎? – Otiel
@LouisRhys - 爲什麼你需要準確地擁有** FileSystemInfo **變量? ** FullPath **或** FullName **返回一個** String **。 **新的FileSystemInfo(路徑).FullPath **沒有任何意義 –
添加一些示例。目前還不清楚你想要什麼。 –
確實背景可能證明我的答案不是你想要的 – Coops
你試過了嗎? –