Path.GetDirectoryName(fpath) c#

I am using Path.GetDirectoryName(fpath) to get me the full path of the file

but what I want to do is just grab the directory from a particular sub direcorty onwards

and also grab the last directory

se using the example below I currently get :

dpath = Path.GetDirectoryName(fpath);

gives me ...

"C:\\Users\\Documents\\Visual Studio 2008\\Projects\\MeasurLink7\\Mitutoyo.MeasurLink.RealTime"

but what I want is

1) from Projects onwards --
dpath1 = "\\MeasurLink7\\Mitutoyo.MeasurLink.RealTime"

2 the last directory

dpath2 = "\\Mitutoyo.MeasurLink.RealTime"

any help would be appreciated
Jayesh AcharyaTechnichal ConsultantAsked:
Who is Participating?
       dpath  = Path.GetDirectoryName(fpath);
        string dir = "Projects";
        string dpath1 = dpath.Substring(dpath.IndexOf(dir) + dir.Length, dpath.Length - (dpath.IndexOf(dir) + (dir.Length * 2)));

        IO.DirectoryInfo dirPath = New IO.DirectoryInfo(dpath);
        string dpath2 = dirPath.Name

You will have to test in C# as this is converted from on the fly
käµfm³d 👽Commented:
eeeewwww....   Substring() calls   : P

While the_o's solution is feasilbe, I think you would benefit from the readability from using something like FileInfo class:
FileInfo info = new FileInfo(path);
string dPath1 = info.FullName.Replace(info.Directory.Parent.FullName, string.Empty);
string dPath2 = info.FullName.Replace(info.Directory.FullName, string.Empty);

Open in new window

:) Wanted 2 give 2 solutions so used substring and directory info. I sometimes take things for granted and expected the user of the solution to interpret (ie if there is a directoryinfo there should be a fileinfo).

Will try to be more concise next time.
käµfm³d 👽Commented:

There's nothing wrong with your proposal. My personal preference is to favor intuitive code for the benefit of those following behind me. Both solutions accomplish the same thing, but I believe what I posted is more evident in its intent. The difference is very negligible though.

I was just kidding you about the Substring() call  = )
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.