1

I have this path: C:\Users\user\Documents\work\Template\workflow.xml

How can I get the part after the folder "Template"? After the "Template" folder other folders can follow. I cannot use the GetDirectoryName method.

Thank You.

loris02
  • 39
  • 5
  • Do you have the path UNTIL the tempalte folder somewhere? Then this is trivial string manipulation (remove configured template folder from beginning of path). You may need to use some Path method to get the similar path or construct it (if the template path is relative), but that is another problem (i.e. get full pathin the same form) and there are methods for this. – TomTom Jul 06 '20 at 09:21
  • So you basically want to convert an absolute path to a relative path. The best answer I saw for this problem until now is this one: https://stackoverflow.com/questions/275689/how-to-get-relative-path-from-absolute-path/32113484#32113484 – Klaus Gütter Jul 06 '20 at 12:07

2 Answers2

1

You can use string.Substring() and string.IndexOf() like so:

using System;

namespace Demo
{
    public static class Program
    {
        static void Main()
        {
            string path = @"C:\Users\user\Documents\work\Template\otherstuff\workflow.xml";
            string target = @"\Template\";

            int index = path.IndexOf(target, StringComparison.OrdinalIgnoreCase);

            if (index >= 0)
            {
                path = path.Substring(index + target.Length);
                Console.WriteLine(path);
            }
            else
            {
                // Error.
            }
        }
    }
}
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
1

You can use this to get the part path between Template and the file name:

string path = @"C:\Users\user\Documents\work\Template\folder1\folder2\\workflow.xml";
string pathToExclude = @"\Documents\work\Template\";
string pathExtracted = null;

if ( path.StartsWith(@"C:\Users\", StringComparison.OrdinalIgnoreCase) )
{
  string directory = Path.GetDirectoryName(path);
  int index = directory.IndexOf(pathToExclude, StringComparison.OrdinalIgnoreCase);
  if ( index > 0 )
    pathExtracted = Path.DirectorySeparatorChar
                  + directory.Substring(index + pathToExclude.Length)
                  + Path.DirectorySeparatorChar;
}

if ( pathExtracted == null )
  Console.WriteLine("Bad path");
else
  Console.WriteLine(pathExtracted);

Result

\folder1\folder2\