Detect if code is running as a service

前端 未结 9 1426
谎友^
谎友^ 2020-12-10 16:30

Is there a way for an .NET library to detect whether or not it is being run as a service?

My library can be run either way. But when its run as a service, developer

9条回答
  •  孤街浪徒
    2020-12-10 16:43

    Seems I am bit late to the party, but topic seems popular. Interesting difference when run as a service is that at app start current folder points to system directory (C:\windows\system32 by default). Its hardly unlikely user app will start from the system folder in any real life situation.

    So, I use following trick (c#):

    protected static bool IsRunAsService()
    {
        string CurDir = Directory.GetCurrentDirectory();
        if (CurDir.Equals(Environment.SystemDirectory, StringComparison.CurrentCultureIgnoreCase))
        { 
             return true; 
        }
    
        return (false);
    }
    

    More details at: https://stackoverflow.com/a/60174944/8494004

提交回复
热议问题