tags:

views:

252

answers:

1

Is there a better way to verify that a C# string is a valid xs:anyURI than the following?

public bool VerifyAnyURI(string anyUriValue)
{ 
    bool result = false;
    try
    {
        SoapAnyUri anyUri = new SoapAnyUri(anyUriValue);
        result = true;
    }
    catch (Exception)
    {
    }
    return result;
}

This constructor doesn't appear to throw any kind of exception. Is any valid string technically a valid anyURI?

+5  A: 

Looking at the SoapAnyUri constructor with Reflector, it doesn't perform any validation at all.

The anyURI data type is defined as follows:

[Definition:] anyURI represents a Uniform Resource Identifier Reference (URI). An anyURI value can be absolute or relative, and may have an optional fragment identifier (i.e., it may be a URI Reference). This type should be used to specify the intention that the value fulfills the role of a URI as defined by [RFC 2396], as amended by [RFC 2732].

So you can simply use Uri.TryCreate with UriKind.RelativeOrAbsolute to verify that a string represents a valid value:

Uri uri;
bool valid = Uri.TryCreate(anyUriValue, UriKind.RelativeOrAbsolute, out uri);
dtb