Get the parent directory and filename

by Erik Lane 6. October 2005 03:42

In a project I'm given the full path to a file, could be nested n depths, and need to return its parent directory and the file name.  I've never really liked doing string manipulation like this as I tend to get lost in the whole addition/subtraction piece of knowing where I am in the string.  Anyway, after few minutes of tinkering I came up with this:

                    if (filePath.IndexOf("\") == -1)
                    {
                        shortFile = filePath;
                    }
                   
else
                    {
                        int lastSlash = href.LastIndexOf("\");
                        int prevSlash = 0;
                        char[] slashes = filePath.ToCharArray(0, lastSlash);
                        for (int i = slashes.GetLowerBound(0); i < slashes.GetLength(0); i++)
                        {
                            if (slashes.GetValue(i).ToString() == "\")
                            {
                                prevSlash = i;
                            }
                        }
                        string modFile = filePath.Substring(prevSlash);
                        shortFile = modFile.Substring(1);
                    }
                    return shortFile;
 
Takes "\testpath\testpath1\file.txt" and return "testpath1\file.txt".  This is a lot cleaner and less code than the why I use to do it in VB and VBScript.
Tags:
Comments are closed