Click here to Skip to main content
15,899,025 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
for eg..: if i have D:\backup\Suresh\Project\Welcome\MyFile\show.jpg
from this path I need only D:\backup\Suresh\Project\
Posted
Comments
Herman<T>.Instance 15-Feb-12 6:01am    
why don't you split the string like string[] mydir = dirstring.Split('\');
Sergey Alexandrovich Kryukov 15-Feb-12 14:23pm    
The mistake of your approach is: '\' is not portable. Did you know that?
No, it's better to use library methods -- please see my answer.
--SA
CodeHawkz 15-Feb-12 6:17am    
You have to tell us on which conditions should you split the path (i.e. on what criteria you decide the place where you want to split the path). An example without that is pretty useless. In which case, the answer given by 'digimanus' is pretty suitable :)
Sergey Alexandrovich Kryukov 15-Feb-12 14:24pm    
You are right, but that method is not suitable by the reason I explained in my comment above; please see my answer.
--SA
ZurdoDev 15-Feb-12 8:08am    
Just write the code to do it. Use String.Substring() or something like it.

1 solution

No, don't split anything and don't use direct string manipulations as other advised.

Instead, first extract the directory using System.IO.Path.GetDirectoryName; see:
http://msdn.microsoft.com/en-us/library/system.io.path.getdirectoryname.aspx[^].

On the result, use the method System.IO.Directory.GetParent required number of times, see:
http://msdn.microsoft.com/en-us/library/system.io.directory.getparent.aspx[^].

Unlike direct string manipulations where you can easily make a mistake, these methods are reliable and platform independent.

—SA
 
Share this answer
 
Comments
Sander Rossel 15-Feb-12 14:42pm    
My 5 for a correct answer.
Sergey Alexandrovich Kryukov 15-Feb-12 14:44pm    
Thank you, Naerling.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900