2

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");
}
4

2 回答 2

1

您运行 Windows 服务的服务帐户无权从您尝试访问的位置读取。您看到的错误与您显示的代码可能存在于 type 的构造中有关ReadFiles

于 2013-06-05T17:35:33.060 回答
0

在运行节点 js 应用程序的 Windows 服务之一中面临类似问题,用于发送电子邮件。当我们从同一目录运行时,它运行良好,但运行与 Windows 服务相同的应用程序时出现问题并且无法发送电子邮件。@meanbunny 的评论确实有帮助,因此将其添加为答案。

如果在代码中将目录/文件作为相对路径提及,Windows 服务将无法访问它们,最好使用绝对路径或更灵活,正如@Mike 在他的评论中提到的那样,为每个服务使用 app.config。

于 2020-02-24T04:50:22.983 回答