C# HttpListener without using netsh to register a URI

Christopher Tarquini picture Christopher Tarquini · Apr 6, 2010 · Viewed 18.5k times · Source

My application uses a small webserver to server up some files and have a web interface for administration remotely. Right now the user has to use netsh to register the URI like so

netsh http add urlacl url=http://+:1233/ user=Chris-PC\Chris

Which is no fun for the average user. I'd like the program to be able to listen on any port specified by the user from my program without the end-user needing to using command prompt. Is there anyway to accomplish this short of just using Process.Start and running command prompt myself?

Answer

chillitom picture chillitom · Apr 12, 2012

I wrote this to elevate perms and add http ACL entries through netsh.

Users will get prompted to make changes top their system but it's better than nothing. You might want to do this in response to an AddressAccessDeniedException

public static class NetAclChecker
{
    public static void AddAddress(string address)
    {
        AddAddress(address, Environment.UserDomainName, Environment.UserName);
    }

    public static void AddAddress(string address, string domain, string user)
    {
        string args = string.Format(@"http add urlacl url={0} user={1}\{2}", address, domain, user);

        ProcessStartInfo psi = new ProcessStartInfo("netsh", args);
        psi.Verb = "runas";
        psi.CreateNoWindow = true;
        psi.WindowStyle = ProcessWindowStyle.Hidden;
        psi.UseShellExecute = true;

        Process.Start(psi).WaitForExit();
    }
}