String extension method which returns the extension of a given filename represented as a string. - CSharp System.IO

CSharp examples for System.IO:File Name

Description

String extension method which returns the extension of a given filename represented as a string.

Demo Code


using System.Text.RegularExpressions;
using System.Text;
using System.Security.Cryptography;
using System.Linq;
using System.Globalization;
using System.Collections.Generic;
using System;/*from   ww w  . j  a v a 2s  . co m*/

public class Main{
        /// <summary>
        /// String extension method which returns the extension of a given filename represented as a string.
        /// </summary>
        /// <param name="fileName">The filename represented as a string on which the method is invoked.</param>
        /// <returns>Returns the file extension of the filename. If the input string is null or whitespace, or the filename has no extension, returns an empty string.</returns>
        public static string GetFileExtension(this string fileName)
        {
            if (string.IsNullOrWhiteSpace(fileName))
            {
                return string.Empty;
            }

            string[] fileParts = fileName.Split(new[] { "." }, StringSplitOptions.None);
            if (fileParts.Count() == 1 || string.IsNullOrEmpty(fileParts.Last()))
            {
                return string.Empty;
            }

            return fileParts.Last().Trim().ToLower();
        }
}

Related Tutorials