在C#中从完整路径返回没有扩展名的文件名

10
我正在寻找一种方法,可以从完整路径中返回文件名,但不包括扩展名。
    private static string ReturnFileNameWithoutExtension(string varFullPathToFile) {
        string fileName = new FileInfo(varFullPathToFile).Name;
        string extension = new FileInfo(varFullPathToFile).Extension;
        return fileName.Replace(extension, "");   
    }

有比用空字符串替换扩展名更可靠的解决方案吗?

4个回答

33
return Path.GetFileNameWithoutExtension (fullpath);

如果您没有完整的路径怎么办? - Boomerang
它们是一样的:“somefile.txt”将返回“somefile”。 - Gonzalo

6
我使用了 System.IO.Path.GetFileNameWithoutExtension(filename);

4

3

另一种解决方案

string fileName = new FileInfo(varFullPathToFile).Name;
fileName=fileName.Substring(0, fileName.LastIndexOf("."));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接