c# - 运行 Windows 服务时出现 FileNotFoundException

标签 c# service directory windows-services

我在 Visual Studio 中有一个生成可执行文件的项目。我已经从该可执行文件创建了一个 Windows 服务。每当我运行它时,它都会失败并出现以下错误:

Error 1053: The service did not respond to the start or control request in a timely fashion.

查看 Windows 事件查看器后,我发现我得到了一个位于项目工作目录中的 FileNotFoundException。这是打开文件的部分:

using (StreamReader file = File.OpenText("configSet.json"))
{
    JsonSerializer serializer = new JsonSerializer();
    configSet = (ConfigSet)serializer.Deserialize(file, typeof(ConfigSet));
}

每当我在 Visual Studio 中或从命令提示符运行该服务时,它都能正常工作。出于某种原因,当我尝试将其作为 Windows 服务启动时,这不起作用。

我还发现,在将文件作为 Windows 服务启动时,对文件路径进行硬编码工作正常。
我想避免这种情况并尽可能使用相对路径(这样我就不必执行代码检查来确定我是从 Visual Studio、命令提示符还是作为 Windows 服务运行该服务)。

最佳答案

您可以使用反射获取可执行文件的路径并将当前目录设置为该路径。以下是如何操作的示例:

String path = System.Reflection.Assembly.GetExecutingAssembly().Location;
path = System.IO.Path.GetDirectoryName(path);
Directory.SetCurrentDirectory(path);

关于c# - 运行 Windows 服务时出现 FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43921789/

相关文章:

python - 重命名/重构目录中文件名的布局

c# - 卸载 Application Insights nuget 包是否安全?

c# - SQLDataReader 行计数

javascript - 计算服务调用收集响应所需的时间

http - super 0.12.x : Implementing Service for a struct

sql-server - 存储 Windows 服务的用户名和密码的最佳方式是什么?

c# - 在执行 File.Move 之前确保文件夹存在的最简单方法是什么?

c# - 是否有像 jXLS 一样使用 c# 和 Excel Interops 模板 excel 的预先存在的解决方案?

c# - 如何从基类的实例创建派生类的实例并包含私有(private)字段?

python - 根据文件名创建文件夹