[英]How can I get a full path of a given path (can be a directory or file, or even full path) using C#?
我得到的最接近的是使用new FileInfo(path).FullPath
,但是据我所知FileInfo仅用于文件,不适用于目录。
有关上下文,请参阅我对Jon Skeet的回答的评论。
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完成此操作。
我想这是-
DirectoryInfo.FullName
尝试这个:
String strYourFullPath = "";
IO.Path.GetDirectoryName(strYourFullPath)
使用扩展了FileSystemInfo
的DirectoryInfo
类,它将为文件或目录提供正确的结果。
string path = @"c:\somefileOrDirectory";
var directoryInfo = new DirectoryInfo(path);
var fullPath = directoryInfo.FullName;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.