How to test is path is unc

דני שטרית 2,266 Reputation points
2024-02-12T14:18:36.81+00:00

Hi, In net 8. string DriectoryName = "\V530-DANIS"; \V530-DANIS => is not unc but new Uri(DirectoryName).IsUnc => return true and also Uri.TryCreate(DirectoryName, UriKind.Absolute, out Uri uri) && uri != null && uri.IsUnc => return true How I can check it return false ? Thanks, Thanks,

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,184 questions
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 44,936 Reputation points
    2024-02-12T15:41:52.72+00:00

    I don't see that behavior. A URL uses /, not \ for pathing. Passing the value you gave to a Uri results in an exception because it cannot figure out what type of URI you're dealing with here.

    var items = new [] {
        "https://tempuri.org",
        "//server/share",
        "//server",
        "/server",
        @"\V530-DANIS"
    };
    
    foreach (var item in items)
    {
        try
        {
            var isUnc = new Uri(item, UriKind.Absolute).IsUnc;
            Console.WriteLine($"{item} = {isUnc}");
        } catch (Exception e)
        {
            Console.WriteLine($"{item} = ERROR: {e.Message}");
        }
    };
    

0 additional answers

Sort by: Most helpful