Returing everything before a character in a string

I would like to return everything to the right of a certain character in a string. Right now i'm using:

            int nPos = strFilePath.LastIndexOf("\\");
            string filename = strFilePath.Substring(nPos + 1);

which returns a filename (ie. test.txt or test2.doc)
What I'm trying to do is return everything before the "." (ie test or test2)

How do I do this?
Mike MillerSoftware EngineerAsked:
Who is Participating?
 
hongjunCommented:
try this

int nPos = strFilePath.LastIndexOf("\\");
string filename = strFilePath.Substring(nPos + 1);
string filenameWithoutExt = filename.Substring(0, filename.IndexOf("."));
Console.Write(filenameWithoutExt);
0
 
drichardsCommented:
If you are dealing exclusively with file paths, use the Path class.  In your case you can use GetFileNameWithoutExtension on the original string (unless you also want the file name with the extension for something).  Try this code to see what the different methods do:


            string p = "C:\\Data\\TestResults\\test.txt";
            Console.WriteLine(Path.GetDirectoryName(p));
            Console.WriteLine(Path.GetExtension(p));
            Console.WriteLine(Path.GetFileName(p));
            Console.WriteLine(Path.GetFileNameWithoutExtension(p));
            Console.WriteLine(Path.GetFullPath(p));
            Console.WriteLine(Path.GetPathRoot(p));
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.