Remove file extension from a file name string

前端 未结 12 1633
一个人的身影
一个人的身影 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 14:45
        /// <summary>
        /// Get the extension from the given filename
        /// </summary>
        /// <param name="fileName">the given filename ie:abc.123.txt</param>
        /// <returns>the extension ie:txt</returns>
        public static string GetFileExtension(this string fileName)
        {
            string ext = string.Empty;
            int fileExtPos = fileName.LastIndexOf(".", StringComparison.Ordinal);
            if (fileExtPos >= 0)
                ext = fileName.Substring(fileExtPos, fileName.Length - fileExtPos);
    
            return ext;
        }
    
    0 讨论(0)
  • 2020-11-27 14:48

    This implementation should work.

    string file = "abc.txt";
    string fileNoExtension = file.Replace(".txt", "");
    
    0 讨论(0)
  • 2020-11-27 14:52

    There's a method in the framework for this purpose, which will keep the full path except for the extension.

    System.IO.Path.ChangeExtension(path, null);
    

    If only file name is needed, use

    System.IO.Path.GetFileNameWithoutExtension(path);
    
    0 讨论(0)
  • 2020-11-27 14:53

    If you want to create full path without extension you can do something like this:

    Path.Combine( Path.GetDirectoryName(fullPath), Path.GetFileNameWithoutExtension(fullPath))
    

    but I'm looking for simpler way to do that. Does anyone have any idea?

    0 讨论(0)
  • 2020-11-27 14:56

    You maybe not asking the UWP api. But in UWP, file.DisplayName is the name without extensions. Hope useful for others.

    0 讨论(0)
  • 2020-11-27 15:00

    You can use

    string extension = System.IO.Path.GetExtension(filename);
    

    And then remove the extension manually:

    string result = filename.Substring(0, filename.Length - extension.Length);
    
    0 讨论(0)
提交回复
热议问题