0

Let's say I have the following path and base directory

string FileDirectory = "/tmp/simple";
string fullPath = "/tmp/simple/s1/s1.txt";

Then how do I find the path of s1.txt relative to FileDirectory without writing a loop?

ie; I want s1/s1.txt as the output.

This looks like the inverse of the Substring operation.

Hence I did like

string relativePath  = fullPath.Substring(FileDirectory.Length, (fullPath.Length - FileDirectory.Length));

Is there any existing function to achieve the same?

Renju Ashokan
  • 428
  • 6
  • 18
  • Does this answer your question? [Getting path relative to the current working directory?](https://stackoverflow.com/questions/703281/getting-path-relative-to-the-current-working-directory) – Franz Gleichmann Jul 20 '21 at 16:25
  • With that, I'm getting output as `simple/s1/s1.txt`. Which is different from `s1/s1.txt` – Renju Ashokan Jul 20 '21 at 16:33

1 Answers1

1

I think you're looking for Path.GetRelativePath(...). Used like this:

string FileDirectory = "/tmp/simple";
string fullPath = "/tmp/simple/s1/s1.txt";

string result = Path.GetRelativePath(FileDirectory, fullPath);
// s1\s1.txt

To get the result with forward slash / instead, you can do a simple Replace() on the result:

result = result.Replace("\\", "/");
// s1/s1.txt
Michael Harris
  • 189
  • 1
  • 10