获取文件的扩展名,而不在路径提供延伸 [英] Get extension of file without providing extension in the path

查看:139
本文介绍了获取文件的扩展名,而不在路径提供延伸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能得到一个文件的扩展名,但是当你指定除扩展之外的整个路径?例如:

Is it possible to get the extension of a file but when you specify the entire path other than the extension? For example:

C:\Users\Administrator\Pictures\BlueHillsTest

C:\Users\Administrator\Pictures\BlueHillsTest

感谢

推荐答案

Directory.GetFiles 将允许您指定一个通配符文件中搜索:

Directory.GetFiles will allow you to specify a wildcard for files to search:

System.IO.Directory.GetFiles(@"C:\temp\py\", "test.*")

对于我来说,返回的3匹配项目的数组。我的期望的数组,因为该目录包含 test.cover test.py ,和 test.pyc

for me, returns an array of 3 matching items. I expect an array, since the directory contains test.cover, test.py, and test.pyc.

如果我使用首先扩展方法:

System.IO.Directory.GetFiles(@"C:\temp\py\", "test.*").First()

那么它只返回的第一个结果( test.cover )。

then it only returns the first result (test.cover).

然而,使用扩展方法

System.IO.Directory.GetFiles(@"C:\temp\py\", "test.*").Single()

提出了一个出现InvalidOperationException 因为序列包含多个元素(这可能是你想要的,根据您的情况)。

raises an InvalidOperationException because the "Sequence contains more than one element" (which might be what you want, depending on your circumstances).

但是,如果我尝试

System.IO.Directory.GetFiles(@"C:\temp\py\", "step.*").Single()

然后,我得到的只是 step.py (也不例外提出),因为这是唯一的文件匹配一步。* 该目录中。

then I get just step.py (no exception raised) because that's the only file matching step.* in that directory.

这篇关于获取文件的扩展名,而不在路径提供延伸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆