Remove file extension from a file name string

前端 未结 12 1694
一个人的身影
一个人的身影 2020-11-27 14:18

If I have a string saying \"abc.txt\", is there a quick way to get a substring that is just \"abc\"?

I can\'t do an fileName.IndexOf(

12条回答
  •  隐瞒了意图╮
    2020-11-27 15:09

    I know it's an old question and Path.GetFileNameWithoutExtensionis a better and maybe cleaner option. But personally I've added this two methods to my project and wanted to share them. This requires C# 8.0 due to it using ranges and indices.

    public static string RemoveExtension(this string file) => ReplaceExtension(file, null);
    
    public static string ReplaceExtension(this string file, string extension)
    {
        var split = file.Split('.');
    
        if (string.IsNullOrEmpty(extension))
            return string.Join(".", split[..^1]);
    
        split[^1] = extension;
    
        return string.Join(".", split);
    }
    

提交回复
热议问题