esac
esac

Reputation: 24685

How to get the relative filename to a specific directory?

I have a method which is doing a file copy. The 'root' is specified by the user on the command line, which I sanitize with Path.GetFullPath(input).

I need to get the path of the file relative to that root, so the following cases would return:

Root        FilePath                    Return
y:\         y:\temp\filename1.txt       temp\filename1.txt
y:\dir1     y:\dir1\dir2\filename2.txt  dir2\filename2.txt

Upvotes: 5

Views: 3834

Answers (4)

SLaks
SLaks

Reputation: 887195

You can write

var relative = new Uri(rootPath).MakeRelativeUri(new Uri(filePath));

http://msdn.microsoft.com/en-us/library/system.uri.makerelativeuri.aspx

Upvotes: 5

James
James

Reputation: 1691

string s1 = "y:\\";
string s2 = "y:\\temp\filename1.txt";
Console.WriteLine(s2.Substring(s1.Length)); \\ Outputs temp\filename1.txt

Hope this helps

Might want to call a .Trim() as well to ensure removing trailing \ characters or the like.

Upvotes: 2

SyntaxGoonoo
SyntaxGoonoo

Reputation: 1070

string relativePath = Path.GetFullPath(input).Replace(rootPath, "");

Upvotes: 1

Katie Kilian
Katie Kilian

Reputation: 6985

System.IO.Path.GetFullPath( filePath ).Substring( rootPath.Length )

Upvotes: 1

Related Questions