Get file extension with file with multiple periods

Getting a 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 application with multiple periods.

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

I want to get a part of the .scene.xmlname.

Update
Extension should also include an initial.

How can I get this from FileInfo?

+4
source share
5 answers

You can use this regular expression to extract all the characters after the period character:

\..*

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

Try

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

Ref. System.IO.Path.GetExtension

.scene.xml, ,

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

.xml - , - scene_a.scene

scene.xml. .

Something like this might do what you want (you will need to add more code to check for conditions in which there is no name at all.):

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

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

Old I know. Discussions about best practices away from you can be made as follows: Linebreaks added for readability.

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

Is this the best way? I do not know, but I know that this works on one line. :) enter image description here

0
source

Keep grabbing the extension until it is no more:

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
0
source

Source: https://habr.com/ru/post/1526280/


All Articles