views:

67

answers:

2

I am writing an HTTP server in C#.

When I try to execute the function HttpListener.Start() I get an HttpListenerException saying "Access Denied".

When I run the app in admin mode in windows 7 it works fine.

Can I make it run without admin mode? if yes how? If not how can I make the app change to admin mode after start running?

thanks.

using System;
using System.Net;

namespace ConsoleApplication1
{
    class Program
    {
        private HttpListener httpListener = null;

        static void Main(string[] args)
        {
            Program p = new Program();
            p.Server();
        }

        public void Server()
        {
            this.httpListener = new HttpListener();

            if (httpListener.IsListening)
                throw new InvalidOperationException("Server is currently running.");

            httpListener.Prefixes.Clear();
            httpListener.Prefixes.Add("http://*:4444/");

            try
            {
                httpListener.Start(); //Throws Exception
            }
            catch (HttpListenerException ex)
            {
                if (ex.Message.Contains("Access is denied"))
                {
                    return;
                }
                else
                {
                    throw;
                }
            }
        }
    }
}
+1  A: 

Can I make it run without admin mode? if yes how? If not how can I make the app change to admin mode after start running?

You can't, it has to start with elevated privileges. You can restart it with the runas verb, which will prompt the user to switch to admin mode

static void RestartAsAdmin()
{
    var startInfo = new ProcessStartInfo("yourApp.exe") { Verb = "runas" };
    Process.Start(startInfo);
    Environment.Exit(0);
}
Thomas Levesque
Can you please explain why I have to start with elevated privileges?
Randall Flagg
You also need to add this line 'startInfo.UseShellExecute = false;' before 'Process.Start(startInfo);'
Randall Flagg
@Randall: because that's how Windows works... a process can't switch to admin mode while it's running. Regarding UseShellExecute: it depends on what you're executing. I tested my code with "notepad.exe", it works fine without UseShellExecute = false
Thomas Levesque
Thanks. About the UseShellExecute: I tried to run the code I posted. Another problem is that for some reason it asked me once if I want to run as administrator and any other time after that it doesn't ask. I restarted, Debugged to make sure it goes there and nothing. any suggestions?
Randall Flagg
Not really... perhaps the second time you were already running it as admin ?
Thomas Levesque
I decided to try and disable the 'startInfo.UseShellExecute = false;' and it worked perfectly. Thank you very very much :)
Randall Flagg