How come my Windows Service cannot access a folder

2019-08-03 06:19发布

问题:

I have setup a Console, Library, and Service project. The Library project loads up files in a folder and stores the text in variables.

The console project will then manipulate those variables. I am able to run the Console project successfully and it loads the files without a problem. The files are set to Copy Always in the DLL and are specified as Content for the Build Action.

When I try to run the exact same code in the service.

File.ReadAllText(@"MyFolder\SomeFile.txt");

It throws the following exception.

The type initializer for 'MyLibrary.Data.ReadFiles' threw an exception.

I am using the Setup Project type to create the installer. After the service installs the folder MyFolder does exist in the Application Folder of the service, as well as the files. What else could be causing my problem for the service not being able to read those files?

EDIT 1

public class ReadFiles {
    public static string DataFile = File.ReadAllText(@"MyFolder\SomeFile.txt");
}

回答1:

The service account that you're running the Windows service under, doesn't have rights to read from the location you're trying to access. The error you're seeing has to do with the fact that the code you showed likely exists in the construction of the type ReadFiles.