关于 c#:Windows 服务给出错误 1053 – System.IO.DirectoryNotFoundException

Windows service gives error 1053 - System.IO.DirectoryNotFoundException

我有一个小型控制台应用程序,其中包含一个用 C# 编写的 Web 服务器。尝试将其转换为 Windows 服务时,出现错误 1053,当我查看错误日志时,它显示:

1
2
3
4
5
6
7
8
9
10
11
Application: YCSWebServerService.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.DirectoryNotFoundException
Stack:
   at HttpServer.Resources.FileResources.Add(System.String, System.String)
   at HttpServer.Resources.FileResources..ctor(System.String, System.String)
   at YCSWebServer.WebServer..ctor(SerialCommunication.SerialCommunicationWrapper, YCSInterfaces.IBuilder, SerialCommunication.SerialCommunication)
   at YCSConfiguration.Builder..ctor()
   at YCSWebServerService.YCSWebServerService..ctor()
   at YCSWebServerService.Program.Main()

这是由于以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
server = new Server();

// Where to find the html page to render
server.Resources.Add(new FileResources("/",".\\\\Webpages"));
server.Add(new FileModule(server.Resources, false));

//Create a http listener
HttpListener listener = HttpListener.Create(IPAddress.Any, 8888);

// use one http listener.
server.Add(listener);

server.RequestReceived += ServerRequestReceived;

// start server, can have max 10 pending accepts.
server.Start(10);

我试图设置一个相对路径到我的 html 文件所在的位置,我试图给它一个固定的路径 fx: c:\\\\\\\\webpages,但没有成功。我总是得到同样的错误。
我是否设置了某种权限/安全性以便我的服务访问此文件夹?
网络服务器基于一个 codeplex 项目:http://webserver.codeplex.com/

我的 onstart 和 onstop 方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public partial class YCSWebServerService : ServiceBase
    {
        private Builder _builder;
        public YCSWebServerService()
        {
            InitializeComponent();
            _builder = new Builder();
        }

        protected override void OnStart(string[] args)
        {
            _builder.Start();
        }

        protected override void OnStop()
        {
            _builder.Stop();
        }
    }

大约一周前我遇到了完全相同的问题。问题是 Windows 服务没有"启动路径"设置,因此解决方案中文件的相对路径不起作用。

此函数获取正在执行服务的文件夹,您需要将其添加到 "\\\\Webpages" 而不是使用 .\\\\WebPages"

希望有帮助

1
2
3
4
5
6
7
private static string ExecutingFolder()
{
    string exeUri = System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase;
    Uri uri = new Uri(exeUri);
    string physicalExePath = uri.LocalPath;
    return IO.Path.GetDirectoryName(physicalExePath);
}

在服务器上,如果开始 -> 运行,输入 services.msc(在服务器 2008 上只需开始 -> 输入 services.msc)并按回车键,您将获得服务列表。在列表中找到您的并查看属性。如果您转到"登录"选项卡,您将看到服务配置为的用户。如果为本地系统设置,则不必担心文件/目录的安全权限。如果设置为其他内容,请确保该帐户可以访问文件/目录。