Please go through my below C# code. I am trying to get the list of Smart Card readers that are now connected to my computer. But this function is returning all the smartcard reader names that was connected in the past (I mean not connected now). I want the list of active (presently) connected readers names only. I am not able to understand where is the issue.
I tried a exe from this website which is written and compiled in C. It is showing only the readers that are connected. I compared the code, but I find no difference. Please help to find a fix.
public static int GetPCSCReaders(out List<string> smartCardReaders, out string errMsg)
{
errMsg = string.Empty;
byte[] readersList = null;
smartCardReaders = new List<string>();
try
{
int hContext = 0;
int ret = SCardEstablishContext(WinSCard.SCARD_SCOPE_USER, 0, 0, ref hContext);
if (ret != 0)
{
errMsg = "WinSCard GetPCSCReader: EstablishContext Error: " + ret.ToString();
return ret;
}
int byteCnt = 0;
ret = WinSCard.SCardListReaders(hContext, null, null, ref byteCnt);
if (ret != SCARD_S_SUCCESS)
{
errMsg = "WinSCard GetPCSCReader: ListReaders Error: " + ret.ToString();
return ret;
}
readersList = new byte[byteCnt];
ret = WinSCard.SCardListReaders(hContext, null, readersList, ref byteCnt);
if (ret != SCARD_S_SUCCESS)
{
errMsg = "WinSCard GetPCSCReader: ListReaders Error: " + ret.ToString();
return ret;
}
int indx = 0;
string readerName = string.Empty;
int i = 0;
while (readersList[indx] != 0)
{
while (readersList[indx] != 0)
{
readerName = readerName + (char)readersList[indx++];
}
smartCardReaders.Add(readerName);
i++;
readerName = "";
indx++;
}
}
catch (Exception ex)
{
errMsg = ex.Message;
}
finally
{
readersList = null;
}
return 0;
}