I have a test class to get the relative path
using System;
using System.IO;
using UnityEngine;
using System.Collections;
public class testType : MonoBehaviour
{
// Use this for initialization
void Start ()
{
Out(@"D:\Data", @"D:\Data\Mail");
Out(@"", @"D:\Data\Mail");
Out(@"D:\Data", @"");
Out(@"D:\Data", @"C:\ICQ\Traf");
Out(@"D:\Project\King\Assets", @"D:\Project\King\Assets\Test");
Out(@"D:\Project\King\Assets", @"D:\Project\Lolo");
}
void Out(string path, string path2)
{
Debug.Log(string.Format("Path1 : {0}
Path2 : {1}
Relative : "{2}"", path, path2 ,RelativePath(path, path2)));
}
public string RelativePath(string fromPath, string toPath)
{
if (String.IsNullOrEmpty(toPath)) return "";
if (String.IsNullOrEmpty(fromPath)) return toPath;
toPath = toPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);// + Path.DirectorySeparatorChar;
fromPath = fromPath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);// + Path.DirectorySeparatorChar;
if (fromPath[fromPath.Length - 1] != Path.DirectorySeparatorChar) fromPath += Path.DirectorySeparatorChar;
Uri fromUri = new Uri(fromPath);
Uri toUri = new Uri(toPath);
if (fromUri.Scheme != toUri.Scheme) { return toPath; } // path can't be made relative.
Uri relativeUri = null;
try
{
relativeUri = fromUri.MakeRelativeUri(toUri);
}
catch
{
relativeUri = toUri;
}
string relativePath = Uri.UnescapeDataString(relativeUri.ToString());
if (toUri.Scheme.ToUpperInvariant() == "FILE")
{
relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
}
return relativePath;
}
}
But not always return the right path:
Path1 : "D:\Data"
Path2 : "D:\Data\Mail"
Relative : "Mail"
Path1 : ""
Path2 : "D:\Data\Mail"
Relative : "D:\Data\Mail"
Path1 : "D:\Data"
Path2 : ""
Relative : ""
Path1 : "D:\Data"
Path2 : "C:\ICQ\Traf"
Relative : "file:\\\C:\ICQ\Traf"
Path1 : "D:\Project\King\Assets"
Path2 : "D:\Project\King\Assets\Test"
Relative : "Test"
Path1 : "D:\Project\King\Assets"
Path2 : "D:\Project\Lolo"
Relative : "..\Lolo"
Error in tests 4 and 6. Help to understand what went wrong.
Windows 7, Unity 4.6