【发布时间】:2026-02-20 10:50:02
【问题描述】:
我正在用 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;
}
}
}
}
}
【问题讨论】:
-
如果有人想避免这个错误,他可以尝试用 TcpListener 编写它。它不需要管理员权限
-
我面临同样的问题,在 Visual Studio 2008 + Windows 7 中,它会产生“拒绝访问”错误,解决这个问题的方法是在管理员模式下运行 Visual Studio 2008
标签: windows-7 c#-4.0 uac httplistener