How do get the first occurrence of a char in Substring
First occurence
String.IndexOf('.')
Last occurence
String.LastIndexOf('.')
file.IndexOf(".")
Should get you the first occurence of ".". Otherwise it will return -1 if not found.
Use IndexOf
and LastIndexOf
string methods to get index of first and last occurrence of "search" string. You may use System.IO.Path.GetExtension()
, System.IO.Path.GetFileNameWithoutExtension()
, and System.IO.Path.GetDirectoryName()
methods to parse the path.
For instance,
string file = @"c:\csnet\info.sample.txt";
Console.WriteLine(System.IO.Path.GetDirectoryName(file)); //c:\csnet
Console.WriteLine(System.IO.Path.GetFileName(file)); //info.sample.txt
Console.WriteLine(System.IO.Path.GetFileNameWithoutExtension(file));//info.sample
Console.WriteLine(System.IO.Path.GetExtension(file)); //.txt
To answer your actual question - you can use string.IndexOf
to get the first occurrence of a character. Note that you'll need to subtract this value from your LastIndexOf
call, since Substring
's second parameter is the number of characters to fetch, not a start and end index.
However... Instead of parsing the names, you can just use Path.GetFilenameWithoutExtension to get the filename directly.