• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 203
  • Last Modified:

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?
0
Mike Miller
Asked:
Mike Miller
1 Solution
 
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

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now