Files
BeWoPlaner/SharedLauncher/Utils/PathUtils.cs
2022-08-30 09:12:20 +02:00

47 lines
2.0 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BS.SharedLauncher.Utils
{
public static class PathUtils
{
/// <summary>
/// Creates a relative path from one file or folder to another.
/// From https://stackoverflow.com/questions/275689/how-to-get-relative-path-from-absolute-path
/// </summary>
/// <param name="beginPath">Contains the directory that defines the start of the relative path.</param>
/// <param name="fullPath">Contains the path that defines the endpoint of the relative path.</param>
/// <returns>The relative path from the start directory to the end path or <c>toPath</c> if the paths are not related.</returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="UriFormatException"></exception>
/// <exception cref="InvalidOperationException"></exception>
public static string MakeRelativePath(string beginPath, string fullPath)
{
if (string.IsNullOrEmpty(beginPath)) throw new ArgumentNullException("fromPath");
if (string.IsNullOrEmpty(fullPath)) throw new ArgumentNullException("toPath");
if (!beginPath.EndsWith(Path.DirectorySeparatorChar.ToString()))
beginPath += Path.DirectorySeparatorChar;
Uri fromUri = new Uri(beginPath);
Uri toUri = new Uri(fullPath);
if (fromUri.Scheme != toUri.Scheme) { return fullPath; } // path can't be made relative.
Uri relativeUri = fromUri.MakeRelativeUri(toUri);
string relativePath = Uri.UnescapeDataString(relativeUri.ToString());
if (toUri.Scheme.Equals("file", StringComparison.InvariantCultureIgnoreCase))
{
relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
}
return relativePath;
}
}
}