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:\dir1\dir2\foo.txt 文件名是 foo.txt,目录名是 C:\dir1\dir2。
C:\dir1\dir2\ 文件名是零长度字符串,目录名是 C:\dir1\dir2。
C:\dir1\dir2 文件名是 dir2,目录名是 C:\dir1。
————————————————
版权声明:本文为CSDN博主「瀚忄」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_30233335/article/details/112865518