Question

Getting the file extension in C# is very simple,

FileInfo file = new FileInfo("c:\\myfile.txt");
MessageBox.Show(file.Extension); // Displays '.txt'

However I have files in my app with multiple periods.

FileInfo file = new FileInfo("c:\\scene_a.scene.xml");
MessageBox.Show(file.Extension); // Displays '.xml'

I want to be able to extract the .scene.xml portion of the name.

Update
The extension should also include the initial .

How can I get this from FileInfo?

Was it helpful?

Solution

You can use this regex to extract all characters after dot symbol:

\..*

var result = Regex.Match(file.Name, @"\..*").Value;

OTHER TIPS

The .xml is the extension the filename is scene_a.scene

If you want to extract scene.xml. You'll need to parse it yourself.

Something like this might do what you want (you'll need to add more code to check for conditions where there isn't a . in the name at all.):

String filePath = "c:\\scene_a.scene.xml";

            String myIdeaOfAnExtension = String.Join(".", System.IO.Path.GetFileName(filePath)
                .Split('.')
                .Skip(1));

Try,

IO.Path.GetExtension("c:\\scene_a.scene.xml");

Ref. System.IO.Path.GetExtension

If you want .scene.xml then try this,

 FileInfo file = new FileInfo("E:\\scene_a.scene.xml");
 MessageBox.Show(file.FullName.Substring(file.FullName.IndexOf(".")));

Continue grabbing the extension until there aren't anymore:

var extensions = new Stack<string>(); // if you use a list you'll have to reverse it later for FIFO rather than LIFO
string filenameExtension;
while( !string.IsNullOrWhiteSpace(filenameExtension = Path.GetExtension(inputPath)) )
{
    // remember latest extension
    extensions.Push(filenameExtension);
    // remove that extension from consideration
    inputPath = inputPath.Substring(0, inputPath.Length - filenameExtension.Length);
}
filenameExtension = string.Concat(extensions); // already has preceding periods

Old I know. Discussions about best practices aside you can do it like this: Linebreaks added for readability.

"." + Path.GetFileNameWithoutExtension(
           Path.GetFileNameWithoutExtension("c:\\scene_a.scene.xml")
      ) 
+ "." +Path.GetExtension("c:\\scene_a.scene.xml")

Is it the best way? I don't know but I do know it works in a single line. :) enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top