繁体   English   中英

运行Windows服务时出现FileNotFoundException

[英]FileNotFoundException when running a Windows Service

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

错误1053:服务未及时响应启动或控制请求。

在查看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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM