In C#, Path.HasExtension() returns true when the file name part of a path has an extension, and false when it does not. For "report.txt" the answer is true; for "README" it is false.
It looks only at the last part of the path, so a dot in a folder name is ignored. A dot at the very end ("file.") is not counted as an extension, because nothing follows it. A null path gives false.
This is a static method of System.IO.Path. Call it as Path.HasExtension(...); there is no new Path(). Like most Path methods, it only works with text: it never opens, reads, or creates a file, and it works the same whether or not the path exists.
Syntax
Pass a path or a file name. The result is a bool.
C#
bool a = Path.HasExtension("report.txt"); // true
bool b = Path.HasExtension("README"); // false
if (!Path.HasExtension(name)) {
name = Path.ChangeExtension(name, ".txt");
}
Call
What it does
HasExtension("a.txt")
Returns true.
HasExtension("README")
Returns false.
HasExtension("file.")
A dot with nothing after it. Returns false.
HasExtension(".gitignore")
Returns true. The last dot starts the name.
HasExtension("/data.v1/log")
The dot is in the folder part. Returns false.
HasExtension(path) is the same as Path.GetExtension(path).Length > 0, just easier to read. It tells you nothing about what the extension is.
Library declarations
C#
public static bool HasExtension(string? path);
public static bool HasExtension(ReadOnlySpan<char> path);
Parameters
Parameter
Description
path
A path or file name to test. It may be null, which gives false. The file does not need to exist.
Return Value
Return Value
Description
bool
true if the last part of the path has a dot followed by at least one character; otherwise false.
C# Examples
Example 1 — Check Four File Names
Print the answer for a normal name, a name without a dot, a trailing dot, and a dot file.
C#
using System;
using System.IO;
class Program {
static void Main() {
string[] names = { "report.txt", "README", "file.", ".gitignore" };
foreach (string name in names) {
Console.WriteLine(name + ": " + Path.HasExtension(name));
}
}
}