Microsoft.CodeAnalysis.Sarif.UriHelper.MakeValidUri C# (CSharp) Method

MakeValidUri() public static method

Create a syntactically valid URI from a path that might be absolute or relative, and that might require percent-encoding.
In general, path might be: 1. Possible to interpret as an absolute path / absolute URI 2. Possible to interpret as a relative path / relative URI 3. Neither We must create a valid URI to persist in the SARIF log. We proceed as follows: 1. Try to create an absolute System.Uri. If that succeeds, take its AbsoluteUri, which (unlike Uri.ToString()) will be properly percent-encoded. 2. Try to create a relative System.Uri. If that succeeds, we want to write it out, but since this is a relative URI, we can't access its AbsoluteUri or AbsolutePath property -- and again, Uri.ToString() does not perform percent encoding. We use this workaround: a. Combine the relative path with an arbitrary scheme and host to form an absolute URI. b. Extract the AbsolutePath property, which will be percent encoded. 3. If all else fails, we have a string that we can't convert to a System.Uri, so just percent encode the whole thing. This should be extremely rare in practice. Thanks and a tip o' the hat to @nguerrera for this code (and for the comment).
public static MakeValidUri ( string path ) : string
path string /// The path to be transformed into a syntactically valid URI. ///
return string
        public static string MakeValidUri(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException(nameof(path));
            }

            Uri uri;
            string validUri;
            if (Uri.TryCreate(path, UriKind.Absolute, out uri))
            {
                validUri = uri.AbsoluteUri;
            }
            else if (Uri.TryCreate(path, UriKind.Relative, out uri))
            {
                UriBuilder builder = new UriBuilder("http", "www.example.com", 80, path);
                validUri = builder.Uri.AbsolutePath;

                // Since what we actually want is a relative path, strip the leading "/"
                // from the AbsolutePath -- unless the input string started with "/".
                if (!path.StartsWith("/", StringComparison.Ordinal) &&
                    !path.StartsWith(@"\", StringComparison.Ordinal))
                {
                    validUri = validUri.Substring(1);

                    // When the UriBuilder constructs an absolute URI, it strips any
                    // leading "." and ".." segments ("dot-segments", as RFC 3986 calls
                    // them). Glue them back on so we don't lose the relative path
                    // information.
                    string leadingDotSegments = GetLeadingDotSegments(path);
                    if (!string.IsNullOrEmpty(leadingDotSegments))
                    {
                        validUri = leadingDotSegments + validUri;
                    }
                }
            }
            else
            {
                validUri = System.Net.WebUtility.UrlEncode(path);
            }

            return validUri;
        }

Usage Example

Esempio n. 1
0
        public static ArtifactLocation CreateFromFilesDictionaryKey(string key, string parentKey = null)
        {
            string uriBaseId   = null;
            string originalKey = key;

            // A parent key indicates we're looking at an item that's nested within a container
            if (!string.IsNullOrEmpty(parentKey))
            {
                key = originalKey.Substring(parentKey.Length).Trim(new[] { '#' });
            }
            else if (key.StartsWith("#"))
            {
                string[] tokens = key.Split(new[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
                uriBaseId = tokens[0];

                // +2 to skip past leading and trailing octothorpes
                key = key.Substring(uriBaseId.Length + 2);
            }

            // At this point, if the key still contains an octothorpe, we are dealing with a
            // reference to a nested item (which we didn't identify because the caller to this
            // utility did not have the parent key in hand).
            if (key.Contains("#"))
            {
                key = key.Substring(key.IndexOf('#')).Trim(new[] { '#' });

                // A uriBaseId is only valid for a location that refers to a root container
                uriBaseId = null;
            }

            return(new ArtifactLocation()
            {
                Uri = new Uri(UriHelper.MakeValidUri(key), UriKind.RelativeOrAbsolute),
                UriBaseId = uriBaseId
            });
        }
All Usage Examples Of Microsoft.CodeAnalysis.Sarif.UriHelper::MakeValidUri