开发者

How to get the relative filename to a specific directory?

I have a method which is doing a file copy. The 'root' is specifie开发者_运维知识库d 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


You can write

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

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


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.


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜