C# - Get the extension of a file that has multiple periods

The .NET method Path.GetExtension() returns everything after the last period, plus the period.

Given the filename: config.xml.txt, it will return .txt.

The code below provides a simple wrapper around Path.GetExtension() that returns all parts of the file extension.

Given the filename: config.xml.txt, it will return .xml.txt.

The code:

using System;
using System.IO;
 
namespace Zuga.net
{
    class Program
    {
        static void Main(string[] args)
        {
            var path = "config.xml.txt";
            var ext = GetExtension(path);
            Console.WriteLine(ext);
        }
 
        private static string GetExtension(string path)
        {
            var ret = "";
            for (; ; )
            {
                var ext = Path.GetExtension(path);
                if (String.IsNullOrEmpty(ext))
                    break;
                path = path.Substring(0, path.Length - ext.Length);
                ret = ext + ret;
            }
            return ret;
        }
    }
}

Program output:

.xml.txt

Ads by Google


Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath