2

Let’s take this string has an example:

D:/firstdir/Another One/and 2/bla bla bla/media/reports/Darth_Vader_Report.pdf

I want to cut the first part of the path:

D:/firstdir/Another One/and 2/bla bla bla

And replace it with **../**, and keep the second part of the path (media/reports/Darth_Vader_Report.pdf)

If I knew the length or size of it, I could use the Replace or Substring. But since the first part of the string is dynamic, how can I do this?


Update

After StriplingWarrior question, I realized that I could have explained better.

The objective is to replace everything behind /media. The “media” directory is static, and will always be the decisive part of the path.

2
  • 2
    How are you determining which part of the path you're trying to replace? Explain the logic: is it everything up to the first time you see the word "/media/"? Commented Oct 27, 2010 at 18:39
  • I have updated my question, I hope this helps. :) Commented Oct 27, 2010 at 18:49

3 Answers 3

3

Use Regular Expressions:

Regex r = new Regex("(?<part1>/media.*)");
var result = r.Match(@"D:/firstdir/Another One/and 2/bla bla bla/media/reports/Darth_Vader_Report.pdf");
if (result.Success)
{
    string value = "../" + result.Groups["part1"].Value.ToString();
    Console.WriteLine(value);
}

Good luck!

Sign up to request clarification or add additional context in comments.

1 Comment

Great! That did it!! :) Thank you so much.
3

You could do something like this:

string fullPath = "D:/firstdir/Another One/and 2/bla bla bla/media/reports/Darth_Vader_Report.pdf"
int index = fullPath.IndexOf("/media/");
string relativePath = "../" + fullPath.Substring(index);

I haven't checked it, but I think it should do the trick.

4 Comments

Normally, I go for the Regex solution, but I'm going to side with a simple .IndexOf(...) this time. +1
This is prone to some gotchas, like the word "Intermediate" somewhere before the "media" you are looking for. You might want to use LastIndexOf. Much would depend on how much of the string you can depend on; so far we only know about "media".
@Jason: It isn't perfect. But I don't think it would match the word "Intermediate", since I check for the index of "/media" - i.e. including the slash. I'll also update my answer to check for "/media/", which should make it even a bit safer.
Since you solution worked well to, I decided to give you a +1. But at the end of the day, I decied to use Homam solution. Thank you anyway :)
0

I would write the following regex pattern,

String relativePath = String.Empty;
Match m = Regex.Match("Path", "/media.*$");
if (m.Success)
{
relativePath = string.Format("../{0}", m.Groups[0].Value);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.