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

来源:互联网 发布:思科acl应用到端口 编辑:程序博客网 时间:2024/04/28 00:50

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);

shipin.lovefcwr.com

结果: www.lovefcwr.com

GetFullPath:C:\dir1\dir2\foo.txt
GetDirectoryName:C:\dir1\dir2
GetFileName:foo.txt
GetFileNameWithoutExtension:foo
GetExtension:.txt
GetPathRoot:C:\ lovefcwr.com

这里要说明 path 是如何判断目录和文件名的:它把最后一个 \ 后面的内容当作是文件名。www.lovefcwr.com

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