C# 轻松获取路径中文件名、目录、扩展名等

来源:互联网 发布:网上赚钱的软件 编辑:程序博客网 时间:2024/04/30 05:56

string path = "C://dir1//dir2//foo.txt";
string str = "GetFullPath:" + Path.GetFullPath(path) + "/r/n";
str += "GetDirectoryName:" + Path.GetDirectoryName(path) + "/r/n";
str += "GetFileName:" + Path.GetFileName(path) + "/r/n";
str += "GetFileNameWithoutExtension:" + Path.GetFileNameWithoutExtension(path) + "/r/n";
str += "GetExtension:" + Path.GetExtension(path) + "/r/n";
str += "GetPathRoot:" + Path.GetPathRoot(path) + "/r/n";
MessageBox.Show(str);

GetFullPath:C:/dir1/dir2/foo.txt
GetDirectoryName:C:/dir1/dir2
GetFileName:foo.txt
GetFileNameWithoutExtension:foo
GetExtension:.txt
GetPathRoot:C:/

这里要说明 path 是如何C# 轻松获取路径中文件名、目录、扩展名等判断目录和文件名的:它把最后一个 / 后面的内容当作是文

件名。

    C:/dir1/dir2/foo.txt 文件名是 foo.txt,目录名是 C:/dir1/dir2。
    C:/dir1/dir2/ 文件名是零长度字符串,目录名是 C:/dir1/dir2。
    C:/dir1/dir2 文件名是 dir2,目录名是 C:/dir1。

原创粉丝点击