loris02
loris02

Reputation: 39

How to get a part of a path in C#?

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.

Upvotes: 1

Views: 88

Answers (2)

user12031933
user12031933

Reputation:

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\

Upvotes: 1

Matthew Watson
Matthew Watson

Reputation: 109567

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.
            }
        }
    }
}

Upvotes: 1

Related Questions