开发者

How can I get a single file name by searching for the extension alone?

I'm using C# with WinForms and I want to get a single file name by searching for the extension alone? I know about the Directory.GetFiles Method, but I'm only looking for a single file. I'm currently using...

 string[] files = Directory.GetFiles(@"c:开发者_高级运维\tpro", "*.fdn");
 string test = files.GetValue(0).ToString();

This works to get the name of the file that ends with .fdn. It works because it will only file in the directory that ends with .fdn. So using Index "0" in this case works. But this just doesn't sit well with me. Is there a better way to go about it?

Thanks


No; this is the only sane way to do it.
However, you're misusing the array; you should write string test = files[0].

In .Net 4.0, you can use the iterator version to avoid fetching more files than needed:

IEnumerable<string> files = Directory.EnumerateFiles(@"c:\tpro", "*.fdn");
string test = files.First();

This will be much faster for enormous directories.


You can also use linq by adding using System.Linq; to your file, and do:

string test = Directory.GetFiles(@"c:\tpro", "*.fdn").FirstOrDefault();

Which will set test to the first found filename, or leave it null if no file was found. Though this is basically the same as your original code, except that your original code will throw an exception if there are no matched files.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜