Reputation: 14185
Right now I'm getting file as a string and I need to iterate through every known ex. case to grab it's file extension.
How can I determine file extension in runtime using c# without iterating for expected?
Upvotes: 0
Views: 271
Reputation: 98848
You can use Path.GetExtension()
method.
The extension of the specified path (including the period "."), or
null
, orString.Empty
. If path isnull
,GetExtension
returnsnull
. If path does not have extension information,GetExtension
returnsString.Empty
.
string p = @"C:\Users\Sam\Documents\Test.txt";
string e = Path.GetExtension(p);
if (e == ".txt")
{
Console.WriteLine(e);
}
Path.GetExtension
checks the entire path for invalid chars. This step is redundant if you already know your path is valid, such as when you received it from Directory.GetFile
s. It looks for a separator char. The implementation checks for DirectorySeparatorChar
, AltDirectorySeparatorChar
, and VolumeSeparatorChar
.
Upvotes: 2
Reputation: 8508
You can use the System.IO.FileInfo Class.
It has a property called Extension which gives you a string containing the extension part of the file name.
FileInfo file = new FileInfo("myfile.txt")
string fileExtension = file.Extension;
Upvotes: 1
Reputation: 3260
An alternative way in finding it..
var file = new FileInfo("myPath");
var extension = file.Extension;
So for example if we wanna take all txt files from a directory we can do like this :
var directory = new DirectoryInfo("myFolder");
var filesWithTxtExtension = directory.GetFiles().Where(file => file.Extension == ".txt");
Upvotes: 1
Reputation: 4182
string path = Path.GetExtension(filePath);
From MSDN - Path.GetExtension Method
Upvotes: 0
Reputation: 4917
string getFileExtension (string Path)
{
return Path.GetExtension(Path);
}
Upvotes: 0
Reputation: 116528
Use Path.GetExtension
:
string extension = Path.GetExtension(@"C:\myfile.txt");
Or, did you mean you want to search for a file with a given base name and any extension? You can use Directory.GetFiles
:
string[] files = Directory.GetFiles(@"C:\", "myfile.*")
Upvotes: 1
Reputation: 166506
Have you tried using something like
The extension of the specified path (including the period "."), or null, or String.Empty. If path is null, GetExtension returns null. If path does not have extension information, GetExtension returns String.Empty.
Upvotes: 2
Reputation: 223392
Use Path.GetExtension method provided by the framework.
The extension of the specified path (including the period "."), or null, or String.Empty. If path is null, GetExtension returns null. If path does not have extension information, GetExtension returns String.Empty.
string extension = Path.GetExtension(@"C:\mydir\file.exe");
You will get .exe
Upvotes: 12