Authentication in WinForms (VB versus C#)


I had a fun issue that I finally got to today. I added a kind of security "audit" feature to a VB application the other day. To do it, I had to get the user name. In VB, it was fairly simple:
 
    Private Function GetUser() As String
        Dim userName As String = Thread.CurrentPrincipal.Identity.Name
        If (userName.Contains("")) Then
            Dim broken As String() = userName.Split("".ToCharArray())
            userName = broken(broken.Length – 1)
        End If
        Return userName
    End Function
 
It was my thought that I could simply "copy" and Sharpify the code and have it work. It would look like this:
 
        private string GetUser()
        {
            string userName = Thread.CurrentPrincipal.Identity.Name;
            if (userName.Contains("\"))
            {
                string[] broken = userName.Split("
\".ToCharArray());
                userName = broken[broken.Length – 1];

            }
            return userName;
        }
 
No dice. I get String.Empty for the user name, as Thread.CurrentPrincipal is a null object. I tried the properties of the application first and found the property pages are completely different. I then tried examining the files in the project, but could not easily figure out the proper file to dink with. Since I am lazy, I looked up the Identy object and after a drill, I find this solution (change to code highlighted):
 
        private string GetUser()
        {
            string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
            if (userName.Contains("\"))
            {
                string[] broken = userName.Split("
\".ToCharArray());
                userName = broken[broken.Length – 1];
            }
            return userName;
        }
 
Now everything is working as expected.
 
Peace and Grace,
Greg
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: