为什么服务中的 File.ReadAllText 会将其目录重置为 "C:\Windows\System32"?

Why does File.ReadAllText in a service reset its directory to "C:\Windows\System32"?

我创建了一个 服务,它也是一个 HTTPServer,我编写了 html 文件并将它们存储在同一工作目录的文件夹中,(比如 E:\My_project\Pages\home.html) 我在 E:\My_project\ 中有一个 Library.cs 文件。在我的代码中有这一行,

string content = File.ReadAllText("Pages/home.html");  

当我尝试阅读这一行时,出现以下错误,

mscorlib: Could not find a part of the path 'C:\WINDOWS\system32\Pages\home.html'

早些时候,它适用于其他一些页面,当我单独对主页进行硬编码并从这些目录中读取 404.html 等其他页面时。现在我已经将主页也添加到 pages 文件夹中,但出现此错误。

我的问题是如何克服这个错误以及为什么 windows 转到 C:\Windows\System32 而不是在与文件相同的目录中查找。

注意:是的,我使用了线程,该服务使用多个线程。

代码:

Library.cs

public static List<Route> GetRoutes() {
        List<Route> routes = new List<Route>();
        string content = File.ReadAllText("Pages/home.html");
        routes.Add(new Route
        {
            Name = "Hello Handler",
            UrlRegex = @"^/$",
            Method = "GET",
            Callable = (HttpRequest request) =>
            {
                return HttpBuilder.GetHome();
            }
        });
        return routes;
}

服务应用程序在对 "current directory" 的理解上类似于常规 Windows 应用程序。当你想访问一个文件并传递一个相对名称时,你的应用程序会尝试通过搜索来找到该文件: 1. 应用程序的加载目录。 2. 当前目录。 3. Windows系统目录。 查看更多详情 here

现在,当前目录对于每个进程都是特定的,它可以在启动时通过参数配置,或者在运行时使用 Directory.SetWorkingDirectory link.

在您的情况下,您需要将工作目录设置为网页所在的目录。