惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Security Affairs
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Jina AI
Jina AI
P
Palo Alto Networks Blog
GbyAI
GbyAI
大猫的无限游戏
大猫的无限游戏
A
Arctic Wolf
Hugging Face - Blog
Hugging Face - Blog
小众软件
小众软件
Y
Y Combinator Blog
T
The Blog of Author Tim Ferriss
Blog — PlanetScale
Blog — PlanetScale
S
Schneier on Security
V
Vulnerabilities – Threatpost
C
Cybersecurity and Infrastructure Security Agency CISA
雷峰网
雷峰网
T
Tenable Blog
人人都是产品经理
人人都是产品经理
T
Tor Project blog
C
Cyber Attacks, Cyber Crime and Cyber Security
AWS News Blog
AWS News Blog
Microsoft Security Blog
Microsoft Security Blog
J
Java Code Geeks
Scott Helme
Scott Helme
SecWiki News
SecWiki News
C
CERT Recently Published Vulnerability Notes
Recorded Future
Recorded Future
I
InfoQ
Security Archives - TechRepublic
Security Archives - TechRepublic
Help Net Security
Help Net Security
Cloudbric
Cloudbric
C
Check Point Blog
Engineering at Meta
Engineering at Meta
TaoSecurity Blog
TaoSecurity Blog
B
Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园_首页
N
News and Events Feed by Topic
云风的 BLOG
云风的 BLOG
MyScale Blog
MyScale Blog
腾讯CDC
量子位
Application and Cybersecurity Blog
Application and Cybersecurity Blog
K
Kaspersky official blog
Vercel News
Vercel News
F
Full Disclosure
T
Troy Hunt's Blog
Forbes - Security
Forbes - Security
S
Security @ Cisco Blogs

博客园 - Lance Yang

批量插入Oracle,遇到CLob字段慢的解决办法 c#,利用WPF的ScaleTransform和TranslateTransform实现图片的缩放效果 自定义控件如何给特殊类型的属性添加默认值 z(转) Oracle 12c心得 Entity Framework Code First (八)迁移 Migrations EF Code First学习笔记 全方位掌握 NSIS 的操作 NSIS学习笔记(转) C#开源框架(整理) 十大前端开发框架(转) .Net 学习 C# 实现无焦点窗体(转载) C++C#时间转换 C#调用C++导出类(转) Socket异步发送的同步控制 自己编码实现数据库的映射实体的代码生成器 C# P/Invoke中传递数组参数 Digital image processing In C# C#数字图像处理(摘录)
C#判断程序是由Windows服务启动还是用户启动
Lance Yang · 2016-06-05 · via 博客园 - Lance Yang

      在Windows系统做网络开发,很多时候都是使用Windows服务的模式,但在调度阶段,我们更多的是使用控制台的模式。在开发程序的时候,我们在Program的Main入口进行判断。最初开始使用Environment.UserInteractive属性,在系统不系统服务的交互模式时,程序运行是正常的,但试过有Win7下,系统允许交互模式,结果在服务启动的时候,跳转到控制台的模式了,服务启动不起来。只能在服务的调用方式下带参数,然后在Main的参数中判断是否为服务方式。这在一般的情况下是可以解决问题的。

      后来有好几个项目,使用了开源的Socket框架,框架本身是通过配置来启动服务的,这样,就没有经过用户的Main方法了,启动带参数的方法不行了,如果为了判断启动模式而加单独的配置,不是很好的做法,通过Program加全局标识是可以解决程序自身启动同框架启动的判断,但服务如果是通过自身的Main启动,又只能靠加参数的方法了,整个实现感觉都是有点别扭。

      在几次的服务程序开发中,遇到一个写文件的路径问题,即取路径总是不对,通过分析,Windows服务启动时的环境默认路径是从System32目录,可能是Windows服务的宿主程序是从这开始的吧,这就有了解决如何判断启动模式的方法了。主要是通过宿主程序是程序集所在的目录来判断。具体如下 :

  string curPath = System.Environment.CurrentDirectory;
  string basePath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory);
  bool isRunWinService = (curPath != basePath);

如果两个路径不相同,我就认为是启动Windows服务了。我们只要在程序的开始做判断,这样Environment.CurrentDirectory的路径还是宿主程序,一般来说,开发人员很少去改动Environment.CurrentDirectory的。这样我们做好的Exe程序支持用户启动,服务启动,或框架自动的服务管理等模式了。