Search code examples
c#httpserver

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


I have created a service that acts also an HTTPServer, I have written html files and stored them in a folder in the same working directory, (say E:\My_project\Pages\home.html ) I have a Library.cs file in E:\My_project\ . In my code I have this line,

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

While I try to read this line, I get the following error,

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

Earlier, it worked for some other pages, when I hardcoded the home page alone and read other pages like 404.html from those directory. Now that I have added the home page also to the pages folder, I get this error.

My Question is how to overcome this error and why does windows go to C:\Windows\System32 rather than looking in the same directory as the file.

NOTE: Yes, I have used threading, the service uses multiple threads.

Code:

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;
}

Solution

  • Service applications are like regular Windows applications in their understanding of "current directory". When you want to access a file and pass a relative name, your application tries to find the file by searching in: 1. The directory where an application is loaded. 2. The current directory. 3. The Windows system directory. See more details here

    Now, the current directory is something specific for every process, it can be configured on startup via parameters, or at runtime using Directory.SetWorkingDirectory link.

    In you case, you need to set your working directory to where you web pages are.