|
dev
newsgroups
|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
My.User.Name returns blank in Console AppHi Folks,
I made aninteresting discovery today in regards to the Visual Basic .NET 2.0 The My namespace My.User.Name returns the username in a Windows form application but does not work in a Windows Console Application. Not sure why. I suspect for security reasons. However I can use most of the other My methods. Can anyone shed some light on what is happening here? I can get the UserName without any problem using System.Environment.Username so why doesn't the My namespace method work? Hi Jamie
Yes, it is indeed an interesting question and a discovery. Answer has to do with the way classes in My namespace are constructed by the VB.Net compiler. It is well documented on MSDN - http://msdn2.microsoft.com/en-us/library/ms233781.aspx - but is not a well known fact. Basically, depending on the type of the project you are creating, classes in My namespace look and behave differently. That is because compiler changes the base class that the generated classes in My namespace derive from. If you look at the abovementioned MSDN page, you'll see that for Console applications MyApplication class derives from ConsoleApplicationBase, and for Windows Forms applications it derives from WindowsFormsApplicationBase. Now deriving from different types does not only change the properites available at run-time (e.g. .CommandLineArgs for Console, but ..SplashScreen for WinForms), but also the behaviour. If you look in the decompile such as Reflector the code for WindowsFormsApplicationBase constructor, you'll see that Thread.CurrentPrincipal is being setup to the current user's Windows identity. This does not happen in the ConsoleApplicationBase. My.User.Name (if you look at implementation) returns the .Name property of the current thread's IPrincipal object. As we've seen it is being setup to WindowsPrincipal in the WindowsFormsApplicationBase constructor in Windows Forms projects, but not in Console projects. Now, for the final part, the reason why Environment.Username property works, is because of its implementation, which calls Win32 native API function to get username of currently logged in Windows user, and is not related to current thread's IPrincipal. There you have it. A lot less mysterious now :-) Cheer, Lev. Jamie Carper wrote: Show quote > Hi Folks, > > I made aninteresting discovery today in regards to the Visual Basic .NET 2.0 > > The My namespace My.User.Name returns the username in a Windows form > application but does not work in a Windows Console Application. Not sure why. > I suspect for security reasons. However I can use most of the other My > methods. > > Can anyone shed some light on what is happening here? I can get the UserName > without any problem using System.Environment.Username so why doesn't the My > namespace method work? |
|||||||||||||||||||||||