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:
This will be much faster for enormous directories.