Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get extension of file without providing extension in the path

Tags:

c#

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

like image 545
GurdeepS Avatar asked Jun 16 '10 16:06

GurdeepS


People also ask

How do I get the string of a file without extension?

GetFileNameWithoutExtension (string? path); The path of the file. The string returned by GetFileName (ReadOnlySpan<Char>), minus the last period (.) and all characters following it.

How do I get the extension of a path?

The following example demonstrates using the GetExtension method on a Windows-based desktop platform. This method obtains the extension of path by searching path for a period (.), starting with the last character in path and continuing toward the first character.

How do I get the extension of a read-only file?

The file path from which to get the extension. The extension of the specified path (including the period, "."), or Empty if path does not have extension information. This method obtains the extension of path by searching path for a period ("."), starting from the last character in the read-only span and continuing toward its first character.

How to get filename without extension in systen without extension?

Systen.IO.Path.net class has GetFileNameWithoutExtension () method to get filename without extension. GetFileNameWithoutExtension (string path) method accept string path as parameter and return filename without extension.


1 Answers

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.

like image 194
Mark Rushakoff Avatar answered Sep 24 '22 13:09

Mark Rushakoff