How to get logged in username after publishing in iis

on Oct 21, 2016 02:25 AM

Hi guys !


I'm publishing a solution using ASP.NET C# and IIS with VS2015, I want to show in a label the Windows username but right it works only local, when I check the published solution it appears the computer name (Ex: 7XS334FC), by the way I'm using the "Environment.GetEnvironmentVariable("username")" method and I've tried with the other ones that are commonly used but nothing. If you could suggest another option to obtain the Windows username using ASP.NET C# that'd be great !



Download FREE API for Word, Excel and PDF in ASP.Net: Download
on Oct 21, 2016 05:01 AM
on Oct 21, 2016 05:37 AM

Hi danlpez07,

Refer the below code.

you need to import the namespace System.Management by adding the reference in the project.

ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
ManagementObjectCollection collection = searcher.Get();
string username = (string)collection.Cast<ManagementBaseObject>().First()["UserName"];

// Or
string username = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

Also refer the below link.

Get username in c# that also works in IIS