954,514 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Getting File Extension

I've been trying to use substring to get the last three digits as part of the extension but wasn't successful.

Can anyone tell me how I can extract the extension from the file name?

Rgs

gallian99
Junior Poster in Training
77 posts since Jan 2009
Reputation Points: 10
Solved Threads: 0
 

Say L is the last character in your filename.(Same as Fname.Length-1)
Then Fname.Substring(L-3,L); should do the trick.

ddanbe
Senior Poster
3,829 posts since Oct 2008
Reputation Points: 2,070
Solved Threads: 661
 

You don't mention if you have to use substring to get the extension or if that is just the method to grab it you decided to use so I'll ask another question . . .

Is there any reason you are not using path.getextension() ?

extension = Path.GetExtension(fileName);


You can get this info from a google search on C# path.getextension or msdn is here: http://msdn.microsoft.com/en-us/library/system.io.path.getextension.aspx

(wondering because .aspx is four while .doc is three etc.)

rapture
Posting Whiz in Training
294 posts since Jul 2007
Reputation Points: 155
Solved Threads: 41
 

After the last "." get the string is after
you may have file, its name readme.program.user.txt!!
It's the time to play with string class, you can also use regular expression and you can use FileInfo.

Ramy Mahrous
Postaholic
2,196 posts since Aug 2006
Reputation Points: 480
Solved Threads: 276
 

*NEVER* make the assumption that a files extension is only 3 characters.

LizR
Posting Virtuoso
1,791 posts since Aug 2008
Reputation Points: 196
Solved Threads: 190
 

try this simple procedure :

private string Getextension(string fileName)
{
string ext = string.Empty;
Boolean hita = false;
int i = fileName.Length - 1;
char[] arr = fileName.ToCharArray();
while(i>0 & !hita)
{
if (arr[i] == '.') hita = true;
else ext = arr[i] + ext;
i = i - 1;
}

return ext;
}

lhavana
Newbie Poster
1 post since Jan 2009
Reputation Points: 10
Solved Threads: 0
 

System.IO.FileInfo fi = new System.IO.FileInfo(FileName);
string ext = fi.Extension.ToString();

kia_mls
Newbie Poster
1 post since Jun 2010
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You