How can I get a full path of a given path (can be a directory or file, or even full path) using C#?

不羁的心 提交于 2019-12-11 01:24:33

问题


The closest I get is using new FileInfo(path).FullPath, but as far as I know FileInfo is for files only, not directory.

See also my comments to Jon Skeet's answer here for context.


回答1:


The Path class also gives you a lot of nice methods and properties, e.g. GetFullPath(). See MSDN for all details.




回答2:


Path.GetFullPath()




回答3:


I think it's-

DirectoryInfo.FullName



回答4:


Try this:

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



回答5:


Use the DirectoryInfo class which extends FileSystemInfo and will give the correct result for either files or directories.

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



回答6:


Use the DirectoryInfo class for paths to directories. Works much in the same matter as FileInfo.

Note that the property for the path is called FullName.

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

If you want to determine whether a path is a file or a directory, you can use static methods from the Path class:

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

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

However, paths could also contain something that might resemble an extension, so you might want to use it in conjunction with some other checks, e.g. bool isFile = File.Exists(path);




回答7:


According to msdn, FileSystemInfo.FullName gets the full path of the directory or file, and can be applied to a 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\



回答8:


You can use file.getdirectory to get this done.



来源:https://stackoverflow.com/questions/7886946/how-can-i-get-a-full-path-of-a-given-path-can-be-a-directory-or-file-or-even-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!