megatron
megatron

Reputation: 51

How to get some parts of the directory c#

For example,

foreach (var imageFile in Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories))
{
    //add to list
}

Output of imageFile = C:\Users\Documents\MyWeb\Slide\Main\slider2.png

I need to get only \Slide\Main\slider2.png

Is there any easy way of doing this?

Upvotes: 0

Views: 228

Answers (5)

Adam Schiavone
Adam Schiavone

Reputation: 2452

I wish I could credit the person who wrote this first, but I've since lost the link.

From my utilities collection:

    /// <summary>
    /// Generates a Relative Path for targetPath, from basePath
    /// </summary>
    /// <param name="basePath">The Directory to start from.</param>
    /// <param name="targetPath">Full Path to file or folder that is to be made relative</param>
    /// <returns>The relative location of targetPath, from basePath</returns>
    /// <remarks>Tested in Util.Tests.IO.PathUtilsTests</remarks>
    public static string MakeRelativePath(string basePath, string targetPath)
    {
        if (basePath == targetPath)
            return "";

        if (!basePath.EndsWith(Path.DirectorySeparatorChar.ToString()))
            basePath += Path.DirectorySeparatorChar;

        if (String.IsNullOrEmpty(basePath)) throw new ArgumentNullException("basePath");
        if (String.IsNullOrEmpty(targetPath)) throw new ArgumentNullException("targetPath");

        var fromUri = new Uri(basePath);
        var toUri = new Uri(targetPath);

        if (fromUri.Scheme != toUri.Scheme) { return targetPath; } // path can't be made relative.

        var relativeUri = fromUri.MakeRelativeUri(toUri);
        var relativePath = Uri.UnescapeDataString(relativeUri.ToString());

        if (toUri.Scheme.Equals("file", StringComparison.InvariantCultureIgnoreCase))
        {
            relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
        }

        return relativePath;
    }

Usage:

var output = @"C:\Users\Documents\MyWeb\Slide\Main\slider2.png";
var basePath = @"C:\Users\Documents\MyWeb\";

var rel = MakeRelativePath(basePath, output);

Upvotes: 0

Ammar Ahmed
Ammar Ahmed

Reputation: 126

You can do it with Uri easily, I have tested it, So it is Working fine

namespace ConsoleApplication1
{
    class Program
    {
        public static void Main()
        {
            Uri uriAddress1 = new Uri("C:\\Users\\Documents\\MyWeb\\Slide\\Main\\slider2.png");
            Console.WriteLine("The parts are {0}{1}{2}", uriAddress1.Segments[5], uriAddress1.Segments[6], uriAddress1.Segments[7]);
            Console.ReadKey();
        }
    }
}

Upvotes: 0

Zinov
Zinov

Reputation: 4119

Why not using string.Split("\") and that will give you all the chunks of that path and then you can concatenate the rest from the position you want, or use a Regular Expressionn as @Zalomon said

Upvotes: 0

Zalomon
Zalomon

Reputation: 553

You can use something like this:

string imageFile = @"C:\Users\Documents\MyWeb\Slide\Main\slider2.png";
string match = System.Text.RegularExpressions.Regex.Match(imageFile,@"\\Slide\\Main\\.*").Value;

Upvotes: 0

DavidG
DavidG

Reputation: 118937

Since you are looking for a specific folder, you can do this:

var imageFile = @"C:\Users\Documents\MyWeb\Slide\Main\slider2.png";
var subFolder = @"\Slide\Main";

var relativePath = imageFile.Substring(
    imageFile.IndexOf(subFolder, StringComparison.OrdinalIgnoreCase));

Upvotes: 1

Related Questions