GurdeepS
GurdeepS

Reputation: 67273

Get extension of file without providing extension in the path

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

Thanks

Upvotes: 8

Views: 4235

Answers (2)

Mark Rushakoff
Mark Rushakoff

Reputation: 258408

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

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

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

If I use the First extension method:

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

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

However, using the Single extension method:

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

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

But if I try

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

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

Upvotes: 16

Darin Dimitrov
Darin Dimitrov

Reputation: 1039408

No it is not possible as you might have both BlueHillsTest.xxx and BlueHillsTest.yyy in this location. Which one do you expect to return in this case?

Upvotes: 2

Related Questions