The following code snippet will let you experiment with the Smart Card reader and the Smart Card directly from the managed code, and you’ll not need to create or use any COM components. But you must be aware of the Smart Card programming APIs with the platform SDK. For a quick start you may want to refer to my previous article of this series, Smart Cards in .NET. (http://www.aspfree.com/c/a/.NET/Smart-Cards-in-.NET/)
Feel free to modify this code in any way you like.
First we fire up the Visual Studio .NET IDE and create a new Windows application in C#. Declare the prototypes as below:
// WinSCard API's to be imported
[DllImport("WinScard.dll")]
public static extern int SCardEstablishContext(uint dwScope,
int nNotUsed1,
int nNotUsed2,
ref int phContext);
[DllImport("WinScard.dll")]
public static extern int SCardReleaseContext(int phContext);
[DllImport("WinScard.dll")]
public static extern int SCardConnect(int hContext,
string cReaderName,
uint dwShareMode,
uint dwPrefProtocol,
ref int phCard,
ref int ActiveProtocol);
[DllImport("WinScard.dll")]
public static extern int SCardDisconnect(int hCard, int Disposition);
[DllImport("WinScard.dll")]
public static extern int SCardListReaderGroups(int hContext,
ref string cGroups,
ref int nStringSize);
[DllImport("WinScard.dll")]
public static extern int SCardListReaders(int hContext,
string cGroups,
ref string cReaderLists,
ref int nReaderCount);
[DllImport("WinScard.dll")]
public static extern int SCardFreeMemory(int hContext,
string cResourceToFree);
[DllImport("WinScard.dll")]
public static extern int SCardGetAttrib(int hContext,
uint dwAttrId,
ref byte[] bytRecvAttr,
ref int nRecLen);
These declarations enable us to use these functions as we’d in our unmanaged C++ code.