Retrieving Passwords from Managed Accounts in SharePoint 2010 for C#

I was looking for a way to retrieve a password from a managed account when I ran into a post titled How to: Get Your Managed Account Passwords When They are Changed Automatically by SharePoint 2010 by Jason Himmelstein. It was written for PowerShell and I needed in C#, so I figured I would post the converted code in case anyone was looking for the same thing. You will need to have the following using statements:

using System.Runtime.InteropServices;
using Microsoft.SharePoint.Administration;

Then you can use the following code to retrieve the managed password:

var managedAccounts = new SPFarmManagedAccountCollection(SPFarm.Local);
foreach (SPManagedAccount managedAccount in managedAccounts)
var securePassword = (SPEncryptedString)managedAccount
System.Reflection.BindingFlags.GetField |
System.Reflection.BindingFlags.Instance |

var intptr = System.IntPtr.Zero;
var unmanagedString = Marshal.

var unsecureString = Marshal.PtrToStringUni(unmanagedString);

//Do something with unsecureString

One caveat to this is that you must be running as a Farm Administrator for the code to succeed. Otherwise you will get an error about accessing the registry. It is also relying on reflection to retrieve a non-public internal field, so as my friend Jeff Burt was quick to point out, Microsoft could change it at any time and break this code. Probably not good for production code.