18

我一直在尝试使用构建事件来启动和停止在我的项目中构建的 Windows 服务。但是,对于 pre 和 post 构建失败,错误级别为 255。我尝试在没有运气的情况下通过 pre-build 捕获这个。

预建

if "$(ConfigurationName)" == "Debug"
(
 net stop myService
 if errorlevel 2 
    if errorlevel 255 
        :exit

   :exit
)

构建后

if "$(ConfigurationName)" == "Release"
(
   copy $(TargetDir) C:\Media\Bin\$(ProjectName)
   if errorlevel 1 BuildEventFailed

   :BuildEventFailed
   mkdir C:\Media\Bin\$(ProjectName)

   copy $(TargetDir) C:\Media\Bin\$(ProjectName)
)
else if "$(ConfigurationName)" == "Debug"
(
   net start myService
)
4

4 回答 4

23

Joel Varty 的以下博客有一个我使用的解决方案: 使用构建事件来重建 Windows 服务,而无需手动停止/启动它

唯一的问题是当您进行重建时。Visual Studio 在预生成事件触发之前清理文件。这当然会失败,因为服务仍在运行。但是常规构建效果很好。希望这可以帮助。

于 2011-07-04T15:35:08.310 回答
1

条件语句不需要双引号 ("")

它应该像

if $(ConfigurationName) == Debug (
 net stop myService
 ...
)
于 2014-01-02T17:47:09.170 回答
1

尝试在预构建代码的第一行使用左括号

于 2011-03-28T10:00:04.347 回答
0

这就是我让它工作的方式:

(这个解决方案是企业软件的一部分,其中一些 dll 文件被另一个应用程序重用)

Model 是一个在 Service 项目中引用的项目,它是在 Service 之前构建的。这就是我们在模型的预构建事件中编写这些代码的原因:


模型预构建事件:

if not exist "$(SolutionDir)UI\bin\Debug\ServiceFolder" mkdir "$(SolutionDir)UI\bin\Debug\ServiceFolder"

net start | find "[Service Name]"

if ERRORLEVEL 0 (
net stop "Service Name"
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe" -u "$(SolutionDir)UI\bin\Debug\ServiceFolder\Service.exe"
)

exit 0
  • 在输出文件夹中创建一个目录
  • 按名称查找服务
  • 停止它
  • 卸载它
  • 如果此处发生错误,则 exit 0 会导致构建过程继续

服务构建后事件:

xcopy /E /Y "$(ProjectDir)bin\Debug\*" "$(SolutionDir)UI\bin\Debug\ServiceFolder"
"C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe" "$(SolutionDir)UI\bin\Debug\ServiceFolder\Service.exe"
net start "Service Name"
  • 将服务所需的所有内容复制到不同的文件夹
  • 安装服务
  • 开始服务

关于权限?

  • Visual Studio 将自动请求提升权限
于 2017-09-01T14:42:57.267 回答