Click here to Skip to main content
15,881,172 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
hi,
i need to split the path below mentioned like

"C:\Program Files\Test1\Test2\Test3\Test4"

1.C:\
2.C:\Program Files\
3.C:\Program Files\Test1\
4.C:\Program Files\Test1\Test2\
5.C:\Program Files\Test1\Test2\Test3\
6.C:\Program Files\Test1\Test2\Test3\Test4

any suggestion on this...
Posted

By using

Directory.GetDirectoryRoot(path)

DirectoryInfo info = Directory.GetParent(path);


these two lines you will get all the results what you want above.
 
Share this answer
 
C#
var path = "C:\Program Files\Test1\Test2\Test3\Test4";

var pathItems = path.Split('\');

var paths = new List<string>();

for(var i = 0; i < pathItems.Length; i++)
{
    var items = pathItems.Skip(0).Take(i+1).ToArray();

    paths.Add(string.Join(@"\", items);
}


The following paths are then contained in the variable "paths".

1.C:\
2.C:\Program Files\
3.C:\Program Files\Test1\
4.C:\Program Files\Test1\Test2\
5.C:\Program Files\Test1\Test2\Test3\
6.C:\Program Files\Test1\Test2\Test3\Test4
 
Share this answer
 
Do you really mean this
C#
public void mysplit(string path)
{
  string[] sa = path.Split(new char[]{'\\'});

  for (int i=0; i < sa.Length; i++)
  {
    string s = (i+1) + "." + sa[0];
    for (int j=1; j<=i; j++)
    {
      s += "\\" + sa[j];
    }
    Console.WriteLine(s);
  }
}


?
 
Share this answer
 
C#
<pre lang="cs">var path = @"C:\Program Files\Test1\Test2\Test3\Test4";

var pathItems = path.Split('\\');

List<String>  paths = new List<String>();
int i=0;
var seed = pathItems[i];

while(i < pathItems.Length-1)
{
paths.Add(seed);
seed = Path.Combine(seed, pathItems[i+1]);
i++;
}
paths.Add(seed);

 
Share this answer
 

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