Question

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");
}
Was it helpful?

Solution

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.

OTHER TIPS

Was facing similar issue in one of the windows service for running node js application, for sending emails. It was running fine when we run from the same directory, but running same application as windows service was having issues and couldn't send emails. Comment from @meanbunny did help, so adding it as an answer.

Windows service can't access the directory/files if they are mentioned in the code as relative path, better use the absolute path or be more flexible as @Mike mentioned in his comment to use app.config for each service.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top