Exemple #1
0
        /// <summary>
        /// 初始化卡
        /// </summary>
        /// <param name="readerList">设备列表</param>
        /// <returns></returns>
        public void InitializeCard(List <string> readerList)
        {
            if (hContext == 0)
            {
                errMsg = "获取设备上下文句柄失败。初始化卡片前需初始化设备!";
                // Log.WriteLog(errMsg);
                throw new Exception(errMsg);
            }

            bool isConnectCard = false;

            for (int i = 0; i < readerList.Count; i++)
            {
                string reader = readerList[i];
                runResult = PCSC.SCardConnect(hContext, reader, 1, 2, ref hCard, ref ActiveProtocol);

                if (runResult != SCARD_SUCCESS)
                {
                    continue;
                }
                else
                {
                    activeReaderName = reader;
                    isConnectCard    = true;
                    break;
                }
            }

            if (!isConnectCard)
            {
                errMsg = "未能搜索到卡片!";
                //  Log.WriteLog(errMsg);
                throw new Exception(errMsg);
            }

            int readerLength = 0;

            int cardStatus = 0;

            int cardProtocal = 0;

            int atrLength = 0;

            runResult = PCSC.SCardStatus(hCard, activeReaderName, ref readerLength
                                         , ref cardStatus, ref cardProtocal, null, ref atrLength);

            if (runResult != SCARD_SUCCESS)
            {
                errMsg = "获取读卡器列表,错误代码为:" + runResult.ToString("X");
                //Log.WriteLog(errMsg);
                throw new Exception(errMsg);
            }

            if (cardStatus != 6)
            {
                errMsg = "卡片状态不合法!连接失败!";
                //Log.WriteLog(errMsg);
                throw new Exception(errMsg);
            }

            byte[] ATR = new byte[atrLength];

            runResult = PCSC.SCardStatus(hCard, activeReaderName, ref readerLength
                                         , ref cardStatus, ref cardProtocal, ATR, ref atrLength);

            if (runResult != SCARD_SUCCESS)
            {
                errMsg = "获取读卡器列表,错误代码为:" + runResult.ToString("X");
                // Log.WriteLog(errMsg);
                throw new Exception(errMsg);
            }
        }