Path.HasExtension Method

Determines whether a path includes a file name extension.

Namespace:  System.IO
Assemblies:   mscorlib (in mscorlib.dll)
  System.Runtime.Extensions (in System.Runtime.Extensions.dll)

public static bool HasExtension(
	string path
)

Parameters

path
Type: System.String

The path to search for an extension.

Return Value

Type: System.Boolean
true if the characters that follow the last directory separator (\\ or /) or volume separator (:) in the path include a period (.) followed by one or more characters; otherwise, false.

ExceptionCondition
ArgumentException

path contains one or more of the invalid characters defined in GetInvalidPathChars.

Starting from the end of path, this method searches for a period (.) followed by at least one character. If this pattern is found before a DirectorySeparatorChar, AltDirectorySeparatorChar, or VolumeSeparatorChar character is encountered, this method returns true.

For a list of common I/O tasks, see Common I/O Tasks.

The following code example demonstrates the use of the HasExtension method.

string fileName1 = "myfile.ext";
string fileName2 = @"mydir\myfile";
string path = @"C:\mydir.ext\";
bool result;

result = Path.HasExtension(fileName1);
Console.WriteLine("HasExtension('{0}') returns {1}", 
    fileName1, result);

result = Path.HasExtension(fileName2);
Console.WriteLine("HasExtension('{0}') returns {1}", 
    fileName2, result);

result = Path.HasExtension(path);
Console.WriteLine("HasExtension('{0}') returns {1}", 
    path, result);

// This code produces output similar to the following: 
// 
// HasExtension('myfile.ext') returns True 
// HasExtension('mydir\myfile') returns False 
// HasExtension('C:\mydir.ext\') returns False

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

XNA Framework

Supported in: 3.0, 2.0, 1.0

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2015 Microsoft