Thursday, January 27, 2011

C# .Net 3.5 Code to replace a file extension using LINQ

I've written this very simple function to replace a file extension using LINQ in C#.NET 3.5 however I have a feeling that there's a more elegant way to do this. (I'm not committed to using LINQ here - just looking for a more elegant approach.) Ideas?

    private string ReplaceFileExtension(string fileName, string newExtension)
    {
        string[] dotSplit = fileName.Split('.');
        return String.Join(".", dotSplit.Take(dotSplit.Length - 1).ToArray()) + "." + newExtension;
    }

(I'm aware of the fact that this won't work if the original file name doesn't have a dot.)

0 comments:

Post a Comment