我正在用C#编写一个HTTP服务器。
当我尝试执行函数HttpListener.Start()
时,会出现HttpListenerException
,错误显示为:
"拒绝访问"
在Windows 7中以管理员模式运行应用程序时,它可以正常工作。
我能否使其在非管理员模式下运行?如果可以,该怎么做? 如果不行,我该如何在启动后将应用程序切换到管理员模式?
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;
}
}
}
}
}