Building a new path-like string from an existing one

You can do this quite tersely with Regex

var newFolder = Regex.Replace(folder, @"\.", @"\$`.");

This matches on each period. Each time it finds a period, it inserts a backslash and then the entire input string before the match ($`). We have to add the period in again at the end.

So, steps are (< and > indicate text inserted by the substitution at that step):

  1. Match on the 1st period. one<\one>.two.three
  2. Match on the 2nd period. one\one.two<\one.two>.three
  3. Result: one\one.two\one.two.three

For bonus points, use Path.DirectorySeparatorChar for cross-platform correctness.

var newFolder = Regex.Replace(folder, @"\.", $"{Path.DirectorySeparatorChar}$`.")

Here's another linqy way:

var a = "";
var newFolder = Path.Combine(folder.Split('.')
    .Select(x => a += (a == "" ? "" : ".") + x).ToArray());

You can try Linq:

  string folder = "one.two.three";
  string[] parts = folder.Split('.');

  string result = Path.Combine(Enumerable
    .Range(1, parts.Length)
    .Select(i => string.Join(".", parts.Take(i)))
    .ToArray());

  Console.Write(newFolder);

Outcome:

 one\one.two\one.two.three 

You can go forward-only in one loop like this:

    var folder = "one.two.three";
    var newFolder = new StringBuilder();

    int index = -1;
    while (index + 1 < folder.Length) {
        index = folder.IndexOf('.', index + 1);
        if (index < 0) {
            newFolder.Append(folder);
            break;
        }
        else {
            newFolder.Append(folder, 0, index);
            newFolder.Append(Path.DirectorySeparatorChar);
        }
    }

You can try it out here.

Tags:

C#

.Net

String