title: Retrieve and use service 'Log on as' credentials in C#
body: <p>I'm currently writing a Windows Service which will be required to interact with an on-premise Exchange server. Quite rightly, we've come to the conclusion that hard-coding the Exchange credentials is a very bad idea, but so is storing them in a config file in plain text. We've come to the conclusion that creating a service account that owns the mailbox in question should satisfy our requirements, however I've hit the following problem:</p>
  
  <p>I've started to use a ManagementObjectSearcher to get the Username of the account running a service on my PC, however I'm not sure how to, or even if, I can get the password. I've tried this:</p>
  
  <pre><code>    class Program
  {
  
      public static ManagementObjectSearcher Searcher = new ManagementObjectSearcher(new SelectQuery("select * from Win32_Service where name = 'netlogon'"));
  
      static void Main(string[] args)
      {
  
          ManagementObjectCollection Response = Searcher.Get();
  
          Console.WriteLine(Response.Count);
  
          foreach (ManagementObject Item in Response)
          {
              Console.WriteLine(Item.ToString());
          }
  
          Console.ReadLine();
      }
  
  }
  </code></pre>
  
  <p>Unfortunately, I don't get a Password back. There's some suggestion from the EWS API documentation (<a href="https://msdn.microsoft.com/en-us/library/office/dn626019(v=exchg.150).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/office/dn626019(v=exchg.150).aspx</a>) that I can grab the credentials of the currently logged in user, but I looked through the referenced code samples and can find no suggestion of how this is doable. </p>
  
  <p>For clarity, I can get the username, that's fine. I need the password... Any help would be appreciated!</p>