November 16, 2011

How to create Relative Path in C#

It is pretty easy to create relative path in C#. Just what you need is to use System.Uri class.

Example:
System.Uri root = new System.Uri( @"C:\TestDir\" );
System.Uri filename = new System.Uri( @"C:\TestDir\MyTestLocation\MyFile.cs" );
System.Uri relativePath = root.MakeRelativeUri( filename )

Console.WriteLine( relativePath.toString() );
At the Output you will see "../MyTestLocation/MyFile.cs".

No comments:

Post a Comment