Returing everything before a character in a string

Posted on 2007-08-10
Last Modified: 2013-11-05
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?
Question by:mwmiller78
    LVL 33

    Accepted Solution

    try this

    int nPos = strFilePath.LastIndexOf("\\");
    string filename = strFilePath.Substring(nPos + 1);
    string filenameWithoutExt = filename.Substring(0, filename.IndexOf("."));
    LVL 19

    Expert Comment

    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";

    Featured Post

    IT, Stop Being Called Into Every Meeting

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    Join & Write a Comment

    Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
    Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
    Need more eyes on your posted question? Go ahead and follow the quick steps in this video to learn how to Request Attention to your question. *Log into your Experts Exchange account *Find the question you want to Request Attention for *Go to the e…
    In this sixth video of the Xpdf series, we discuss and demonstrate the PDFtoPNG utility, which converts a multi-page PDF file to separate color, grayscale, or monochrome PNG files, creating one PNG file for each page in the PDF. It does this via a c…

    728 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    14 Experts available now in Live!

    Get 1:1 Help Now