Method replys unplugged NFC readers

2019-09-02 14:08发布

问题:

I currently use pcsc-sharp to read ids from NFC tags. I got this methode to lists all available readers. But this replys me all readers I ever used. There are also old readers listed that aren´t plugged in. Does anyone know how to fix that?

public void SelectDevice()
        {
            List<string> availableReaders = this.ListReaders();
            this.RdrState = new Card.SCARD_READERSTATE();
            readername = availableReaders[0].ToString();
            this.RdrState.RdrName = readername;
        }


public List<string> ListReaders()
            {
                int ReaderCount = 0;
                List<string> AvailableReaderList = new List<string>();

                retCode = Card.SCardListReaders(hContext, null, null, ref ReaderCount);
                if (retCode != Card.SCARD_S_SUCCESS)
                {
                    MessageBox.Show(Card.GetScardErrMsg(retCode));
                }

                byte[] ReadersList = new byte[ReaderCount];
                retCode = Card.SCardListReaders(hContext, null, ReadersList, ref ReaderCount);
                if (retCode != Card.SCARD_S_SUCCESS)
                {
                    MessageBox.Show(Card.GetScardErrMsg(retCode));
                }
                string rName = "";
                int indx = 0;
                if (ReaderCount > 0)
                {
                while (ReadersList[indx] != 0)
                {
                while (ReadersList[indx] != 0)
                {
                    rName = rName + (char)ReadersList[indx];
                    indx = indx + 1;
                }
                AvailableReaderList.Add(rName);
                rName = "";
                indx = indx + 1;
            }
        }
        return AvailableReaderList;
    }

回答1:

Okay I think I solved the problem. Don´t know if this is the best way, but it works. I also don´t know why the ListReaders()-Method delivers me all readers I ever used, but I found another way to get the reader name of the reader that is currently plugged in.

public void SelectDevice()
        {
            string[] readerNames = new string[1];
            using (var context = new SCardContext())
            {
                context.Establish(SCardScope.System);
                readerNames = context.GetReaders();
            }
            readername = readerNames[0];
            this.RdrState.RdrName = readername;
        }

If there´s a better way, or someone knows why I get all readers ever used, please comment.