我在 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/