请浏览我下面的 C# 代码。我正在尝试获取现在连接到我的计算机的智能卡读卡器列表。但是这个函数会返回过去连接的所有智能卡读卡器名称(我的意思是现在没有连接)。我只想要活动(当前)连接的读者名称列表。我无法理解问题出在哪里。
我尝试了这个网站上的一个 exe,它是用 C 编写和编译的。它只显示连接的读者。我比较了代码,但我发现没有区别。请帮助找到解决方法。
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;
}