System.Uri.MakeRelativeUri C# (CSharp) Method

MakeRelativeUri() public method

public MakeRelativeUri ( Uri uri ) : Uri
uri Uri
return Uri
        public Uri MakeRelativeUri(Uri uri)
        {
            if ((object)uri == null)
                throw new ArgumentNullException(nameof(uri));

            if (IsNotAbsoluteUri || uri.IsNotAbsoluteUri)
                throw new InvalidOperationException(SR.net_uri_NotAbsolute);

            // Note that the UserInfo part is ignored when computing a relative Uri.
            if ((Scheme == uri.Scheme) && (Host == uri.Host) && (Port == uri.Port))
            {
                string otherPath = uri.AbsolutePath;

                // Relative Path
                string relativeUriString = PathDifference(AbsolutePath, otherPath, !IsUncOrDosPath);

                // Relative Uri's cannot have a colon ':' in the first path segment (RFC 3986, Section 4.2)
                if (CheckForColonInFirstPathSegment(relativeUriString)
                    // Except for full implicit dos file paths
                    && !(uri.IsDosPath && otherPath.Equals(relativeUriString, StringComparison.Ordinal)))
                    relativeUriString = "./" + relativeUriString;

                // Query & Fragment
                relativeUriString += uri.GetParts(UriComponents.Query | UriComponents.Fragment, UriFormat.UriEscaped);

                return new Uri(relativeUriString, UriKind.Relative);
            }
            return uri;
        }

Usage Example

Example #1
1
        public static string GenerateRelativePath(string from, string to)
        {
            if(String.IsNullOrWhiteSpace(from) || String.IsNullOrWhiteSpace(to))
            {
                throw new ArgumentNullException("Requires paths");
            }

            Uri fromUri = new Uri(from);
            Uri toUri = new Uri(to);

            //The URI schemes have to match in order for the path to be made relative
            if(fromUri.Scheme != toUri.Scheme)
            {
                return to;
            }

            Uri relativeUri = fromUri.MakeRelativeUri(toUri);
            string relative = Uri.UnescapeDataString(relativeUri.ToString());

            //If neccessary to do so, normalise the use of slashes to always be the default for this platform
            if(toUri.Scheme.ToUpperInvariant() == "FILE")
            {
                relative = relative.Replace(Path.AltDirectorySeparatorChar,
                    Path.DirectorySeparatorChar);
            }

            return relative;
        }
All Usage Examples Of System.Uri::MakeRelativeUri